Passing variable into page.evaluate - PhantomJS

Antoine picture Antoine · Mar 12, 2013 · Viewed 24.1k times · Source

Is it possible to pass variables in a page.evaluate in my case below?

function myFunction(webpage, arg1, arg2){

var page = require('webpage').create();

page.viewportSize = { width: 1920, height: 1080 };

page.open(webpage, function (status){

    if (status == 'success') {

            page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js", function(){

                page.evaluate(function(){

                    arg = arg1 + arg2;
                    console.log(arg);

                });

            });

    } 

    else { phantom.exit(); }

});

}

I tried several methods found on the internet but nothing actually impossible to get to its variables.

Thank you in advance for your help :)

Answer

Ariya Hidayat picture Ariya Hidayat · Mar 12, 2013

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);