Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

define page evaluate outside of page open in phantomjs

in the basic example of open a web page with phantomjs we use below code for open web and evaluate when page open complete in a function .

var page = require('webpage').create();
page.open('http://www.sample.com', function() {
  page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
    page.evaluate(function() {
           console.log(document.title);
    });
    phantom.exit()
  });
});

is any way that let us define page.evaluate in a function out side of page.open callback function for call it any time we need and no just after page open

like image 940
MOB Avatar asked Nov 20 '25 01:11

MOB


1 Answers

not sure what exactly do you mean, but from what I've understood from your example this could help maybe:

var page = require('webpage').create();
// document is already initialized
document.title = 'internal call';

page.onConsoleMessage = function (msg, lineNum, sourceId) {
    console.log('PAGE\'S CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};

var func = function () {
    console.log('Title: ', document.title);
}

// calling outside of the page.open:
func();

page.open('http://google.com/', function () {
    page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
        // calling inside:
        page.evaluate(func);
        page.close();
        phantom.exit(0);
    });
});

Also there is a Note for page.evaluate function about arguments and closures

like image 125
Andrey Borisko Avatar answered Nov 21 '25 15:11

Andrey Borisko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!