简体   繁体   中英

PhantomJS: How to access global functions and variables?

I am trying to run a .js through PhantomJS and use some global functions or variables from within the page context.

Here is a minimal example:

var page = require('webpage').create(); // or: var page = new WebPage();

// reroute page's console to global console
page.onConsoleMessage = function(msg) { console.log(msg) }

function Foo(x) { return "bar"+x }

page.open( 'https://www.example.com/', function(){

    console.log(Foo(1)); // works OK

    page.evaluate( function(){

        console.log('test'); // works OK (message appears because we rerouted 
                             // the page's console to global console output)

        console.log(Foo(2)); // does NOT work, Foo is unknown
    });

    console.log(Foo(3)); // works OK
    phantom.exit();

});

Note how the Foo() function is not known within the context of the page's evaluate() function.

I've tried numerous approaches, such as doing page.Foo2 = Foo; right below the definition of Foo and then within the evaluate context I call Foo2(2) , but nope.

Or page.Foo2 = function(x) { return Foo(x) } but again, to no avail. Also not by calling this.Foo2(2) instead of just Foo2(2) (if that even makes sense).

How do I access functions or variables outside the page scope?

You can declare a function in the sandbox context:

page.open( 'https://www.example.com/', function(){

    page.evaluate( function(){

        function Foo(x) { return "bar"+x }

        console.log(Foo(2));
    });

    phantom.exit();
});

Or, if you need to use it in the global context too, you can send it into the sandbox:

function Foo(x) { return "bar"+x }

page.open( 'https://www.example.com/', function(){

    console.log(Foo(1));

    page.evaluate( function(Foo){

        console.log(Foo(2));

    }, Foo);

    console.log(Foo(3));

    phantom.exit();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM