Aaron Loften Aaron Loften - 1 month ago 14
jQuery Question

CasperJS - using jQuery. ReferenceError: Can't find variable: jQuery/$

I'm writing code that involves jQuery in CasperJS. By chance, could someone point out the error I've made in including jQuery? (After 45 minutes of searching, I'm starting to think it's a local problem.)

I have tried both of the following:

casper.page.injectJs('C:\sweeps\jquery-1.10.2.min.js');


and

var casper = require('casper').create({
clientScripts: ["C:\sweeps\jquery-1.10.2.min.js"]
});


Code:

// sample.js
var casper = require('casper').create();

var login = "some username";
var password = "some password";

casper.start('https://www.paypal.com/us/home', function() {
this.fillXPath('form.login', {
'//input[@name="login_email"]': login,
'//input[@name="login_password"]': password,
}, true);
});

casper.page.injectJs('C:\sweeps\jquery-1.10.2.min.js');

$("input[name='submit.x']").click();

setTimeout(function(){
setTimeout(function(){

casper.run(function() {

this.captureSelector('example2.png', '#page');

this.echo('Done.').exit();

});

}, 30000); }, 1);


Output:

ReferenceError: Can't find cariable: jQuery
C:/sweeps/test2.js:21


The same result comes when "jQuery" is switched to "$".

EDIT: I've also tried relative pathing.

My reference is: Can I use jQuery with CasperJS?

Answer

Read this Casper#evaluate()

The concept behind this method is probably the most difficult to understand when discovering CasperJS. As a reminder, think of the evaluate() method as a gate between the CasperJS environment and the one of the page you have opened; everytime you pass a closure to evaluate(), you’re entering the page and execute code as if you were using the browser console.

casper.evaluate(function() {
    $("input[name='submit.x']").click();
});

You need to use the jQuery selector as if you were in a browser.