简体   繁体   English

PhantomJS:如何访问全局函数和变量?

[英]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. 我试图通过PhantomJS运行.js,并在页面上下文中使用一些全局函数或变量。

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. 请注意,在页面的evaluate()函数的上下文中如何知道Foo() evaluate()函数。

I've tried numerous approaches, such as doing page.Foo2 = Foo; 我尝试了许多方法,例如执行page.Foo2 = Foo; right below the definition of Foo and then within the evaluate context I call Foo2(2) , but nope. Foo定义的正下方,然后在evaluate上下文中,我调用Foo2(2) ,但不。

Or page.Foo2 = function(x) { return Foo(x) } but again, to no avail. page.Foo2 = function(x) { return Foo(x) }但同样无济于事。 Also not by calling this.Foo2(2) instead of just Foo2(2) (if that even makes sense). 也不要通过调用this.Foo2(2)而不是仅Foo2(2) (如果这样还可以)。

How do I access functions or variables outside the page scope? 如何访问page范围之外的函数或变量?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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