casperJS failed Injecting jQuery

2019-05-27 04:41发布

问题:

Does anyone know how come I am encountering

[warning] [phantom] Failed injecting %s client side. 
Failed injecting includes/jquery-1.10.2.min.js client side 

when I have included

'includes/jquery-1.10.2.min.js' 

within the Casper constructor. Someone posted a similar question here: https://groups.google.com/forum/#!msg/casperjs/hY4ziaoXIEE/YFi8Sj4JysMJ, but I do not understand how they have incorporated the casper.evaluate() in their solution:

casper.then( function() {
this.evaluate(function($) {
console.log($('title').text());
}
}); 

回答1:

I don't remember ever being able to inject scripts using the clientScripts option of the CasperJs constructor. Instead I have found the following works for me always.

casper = require('casper').create();
casper.start();
casper.open('some url');
casper.then(function doSomething() {
    this.page.injectJs('relative/local/path/to/jquery.js');
    var items = this.evaluate(function () {
        return $('div.someClass'); // jquery here
    });
});


回答2:

What tripped me up was that the path to the include is relative to the directory you are calling the script from, NOT the directory the script actually resides in.