3

I'm new to phantomJS and this is what I tried so far:

var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);

page.settings.userAgent = 'SpecialAgent';
page.open('http://google.com', function (status) {
    if (status !== 'success') {
        console.log( 'Unable to access network' );
    } else {
        console.log( 'Opened ok' );
        page.includeJs( 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function() {
            console.log( 'include JS callback' );
            page.evaluate(function(){
                console.log('include JS callback - eval');
            });
        });
        console.log( 'After include JS' );
    }
    phantom.exit();
});

but the output is

The default user agent is Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34
Opened ok
After include JS

As you can see 'include JS callback' and 'include JS callback - eval' are not logged, where is the problem?

Betlista
  • 10,327
  • 13
  • 69
  • 110

1 Answers1

12

Fastest gun in the west Phantom-style problem. You're exiting too early. page.includeJs is an asynchronous function, because it has to send a request to fetch the resource. You can see that, because it has a callback. You should move the phantom.exit(); to the end of the page.includeJs callback. All further processing should also be triggered from/moved to the page.includeJs callback.

If you want 'include JS callback - eval' to appear you have to additionally register to the page.onConsoleMessage event.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
  • Just a link to this registration - http://stackoverflow.com/questions/16701208/phantomjs-page-evaluate-not-logging-onto-console – Betlista Nov 13 '14 at 21:31
  • No, it was for others (if someone finds this in future), how to use this `page.onConsoleMessage`, I'm sure you know ;-) – Betlista Nov 13 '14 at 22:46