Reputation: 11130
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?
Upvotes: 1
Views: 1012
Reputation: 16838
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();
});
Upvotes: 1