Passing variable into page.evaluate - PhantomJS

I have phantomjs 1.5.0, so instead of compiling 1.6 or higher version I went for an alternative solution:

So I've saved arguments to selectors.js file

-------------selectors.js starts----------------
var selectors = "div.nice"
-------------selectors.js   ends----------------

and then injected them into the page:

page.injectJs("selectors.js");

More details can be found here: http://phantomjs.org/api/webpage/method/inject-js.html


As usual, the answer is clearly stated in the documentation of evaluate function:

As of PhantomJS 1.6, JSON-serializable arguments can be passed to the function. In the following example, the text value of a DOM element is extracted. The following example achieves the same end goal as the previous example but the element is chosen based on a selector which is passed to the evaluate call:

The example that follows demonstrates the usage:

var title = page.evaluate(function(s) {
    return document.querySelector(s).innerText;
}, 'title');
console.log(title);

Tags:

Phantomjs