I am trying to use jquery with phantomjs. I tried a standalone example and it worked fine. Here is what I did:
var page = require('webpage').create(); page.open("http://www.phantomjs.org", function(status) { page.onConsoleMessage = function(msg) { console.log("message recvd: " + msg); }; var result; page.includeJs("https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js", function() { console.log("loading jquery"); }); setTimeout(function() { page.evaluate(function() { console.log("$(\"title\").text() -> " + $("title").text()); }); }, 1000); }
Here is the result I got:
loading jquery message recvd: $("title").text() -> PhantomJS | PhantomJS
In the code snippet above, I used setTimeout () for the evaluation function, because includeJs () did asynchronously and it took some time to load jquery. If I do not use setTimeout () or use a small value for the timeout, it does not work.
However, when I try to use the same code in my application, it does not work. Here is what I have:
var baseSetup = function(guid, page, config, request, response) { page.onConsoleMessage = function (msg) { console.log(guid + ": console msg: " + msg); }; page.onAlert = function (msg) { console.log(guid + " (alert): alert msg: " + msg); }; page.onError = function(msg, trace) { var msgStack = ['ERROR: ' + msg]; if (trace && trace.length) { msgStack.push('TRACE:'); trace.forEach(function(t) { msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : '')); }); } console.error(guid + ": " + msgStack.join('\n')); }; } module.exports = function extractionDriver(responseFromUrl, responseToUser, page, request) { console.log(page.customHeaders['guid'] + ": extractionDriver, status = " + responseFromUrl.status); if(page.isLocalFile || responseFromUrl.status !== 0) { var viewportStr = page.customHeaders['viewportStr']; console.log(page.customHeaders['guid'] + ": Setting viewport size: " + viewportStr); var viewportObj = parseViewport(viewportStr); page.viewport = viewportObj; page.evaluate(function(w,h) { document.body.style.width = w + "px"; document.body.style.height = h + "px"; }, viewportObj.width, viewportObj.height); page.includeJs("https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js", function() { console.log("loading jquery"); }); setTimeout(function() { page.evaluate(function() { console.log("$(\"title\").text() -> " + $("title").text()); }); }, 1000); }
And this is what I see when the application starts:
d8db6045-a0e8-11e4-a619-6949593d958d: ERROR: ReferenceError: Can't find variable: $ TRACE: -> phantomjs:
The jquery download log line is never printed, and jquery is never loaded.
I tried wrapping the calculate () function inside the includeJs () callback, but that didn't work either (no console logs were printed).
What could be wrong here? Please let me know if I need to provide more information.