PhantomJS evaluate with basic auth returning null

2019-02-28 13:36发布

问题:

I am trying to use PhantomJS on a page with basic always auth, for example, this page

http://alexturpin.net/auth (test:rosebud)

Using the following code

var webpage = require('webpage');

page = webpage.create();
page.settings = {
    userName: "test",
    password: "rosebud"
};

page.open("http://alexturpin.net/auth/", function(status) {
    console.log(status);
    var retval = page.evaluate(function() {
        return "test";
    });
    console.log(retval);
});

I get this output

$ phantomjs test.js
success
null

Whatever I try, evaluate will keep returning null, even though the page seems to have been opened fine because status contains "success".

If I decide to open a page with no basic auth, like http://alexturpin.net/noauth, I still get the same results. Only when I finally remove the authentication settings altogether before opening the page does it work.

The use of authentication settings seem to be conflicting with the evaluate. Is this a bug in PhantomJS, or did I miss something?

回答1:

With that syntax you are wiping out the settings object, replacing it with only userName and password. Use that code to set them:

page.settings.userName = "test";
page.settings.password = "rosebud";

Probably PhantomJS should handle that better, i.e. not rely on the settings object for defaults.



回答2:

This is a closure issue, try to put your console.log in a callback