I'm trying to test a chrome plugin by simulating part of what it's doing on phantomjs.
What I want phantom to do seems extremely simple, and yet I'm having problems. I want it to visit a certain web page and in the context of this page run a script that will send an ajax request to my backend and print out the response. To make my life easier, I want phantom to use jQuery for sending ajax requests.
So here’s the script test1.js that I’m passing to phantom:
var page = new WebPage(), url = 'http://www.example.com', // Callback is executed each time a page is loaded... page.open(url, function (status) { if (status === 'success') { console.log('opened url'); start(); } }); function start(){ page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', function() { console.log("got here"); $.get("http://my-wonderful-site.com") .done(function( data ) { console.log("here!"); console.log(data); phantom.exit(); }); }); } The console output of the command phantomjs test1.js --web-security=false is:
opened url got here ReferenceError: Can't find variable: $ test1.js:20 :/modules/webpage.js:337 So it seems that even jQuery doesn’t get loaded, but I can't figure out what I am doing wrong. Tried page.injectJs to inject jQuery from my hard drive, but got the same error. Could you please help?
Edited:
Updated the function as suggested:
function start(){ page.includeJs('https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js', function() { console.log("got here"); page.evaluate(function() { console.log("and here"); $.get("http://my-wonderful-site.com") .done(function( data ) { console.log("here!"); console.log(data); phantom.exit(); }); }); }); } Now phantom just hangs, and the console output is:
phantomjs test1.js --web-security=false opened url got here That is, the console.log immediately before the $.get doesn't even execute.