zbMax
zbMax

Reputation: 2818

Variable declared as const within page.evaluate() is not being used in PhantomJS

I've got a function which works great on a standard browser (ie, firefox, chrome,...) but some part of it doesn't with PhantomJS.

So, I have a file - let name it script1.js - which looks like this :

const CONST1 = 1;

function f1()
{
    //...
    myVar = (typeof myVar === "undefined") ? CONST1 : myVar;
    //...
}

And here is a sample of the script run by PhantomJS:

var page = webPage.create();

page.open(url,function(status){ 
    if (page.injectJs('script1.js')) {
        page.evaluate(function(){
            //...
            f1();
            //...
        });
    }
});

Using PhantomJS, if myVar is not set, it doesn't takes the value of CONST1 and still undefined. Indeed, CONST1's value is undefined. If I change for :

myVar = (typeof myVar == "undefined") ? "value" : myVar;

myVar will be "value".

Is there a way to use constants with PhantomJS?

Upvotes: 2

Views: 994

Answers (2)

Artjom B.
Artjom B.

Reputation: 61952

PhantomJS supports the const keyword with the same behavior as var. This means that you can re-assign variables that are declared as const. The following code works as-is in PhantomJS 1.9.7 and 2.0.0.

phantomscript.js

var page = require("webpage").create();

page.open("http://example.com",function(status){ 
    if (page.injectJs('inc.js')) {
        console.log("out: " + page.evaluate(function(){
            f1();

            return myVar;
        }));
        phantom.exit();
    }
});

inc.js

const CONST1 = 1;

function f1()
{
    myVar = (typeof myVar === "undefined") ? CONST1 : myVar;
}

output

$ phantomjs phantomscript.js
out: 1

I suspect the issue was that you were trying to access CONST1 outside of the page context. PhantomJS has two contexts with the page context being sandboxed. What happens in the page context, stays in the page context (except if you explicitly pass it outside). I suggest that you read the documentation to page.evaluate() carefully.

There is also a nice picture in the CasperJS documentation:

enter image description here

Upvotes: 2

skywritergr
skywritergr

Reputation: 158

PhantomJS doesn't really support ES6 (ES2015) features as of yet. It will come when the new V8 integration arrives (which i think it did already so i'm hoping soon).

Here is an open defect on github (it talks about karma but gives you an idea) and also there are plenty of answers on how to use ES6 with PhantomJS.

Upvotes: 2

Related Questions