I am currently in the process of testing a chrome plugin by emulating a portion of its functionality on phantomjs.
My objective for phantom seems quite straightforward, yet I am encountering issues. I aim for it to navigate to a specific webpage and within that page's context, execute a script that will send an ajax request to my backend and display the response. To simplify matters, I prefer phantom to utilize jQuery for ajax requests.
Below is the script test1.js
that I am providing 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 output in the console when running the command
phantomjs test1.js --web-security=false
is as follows:
opened url
got here
ReferenceError: Can't find variable: $
test1.js:20
:/modules/webpage.js:337
It appears that even jQuery fails to load, and I am unable to determine my mistake. I attempted using page.injectJs to inject jQuery from my local drive, yet encountered the same error. Could you offer assistance?
Edited:
Following the suggested advice, I updated the function:
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 simply hangs, and the console output displays:
phantomjs test1.js --web-security=false
opened url
got here
Specifically, the console.log statement right before the $.get
call does not execute at all.