CasperJS inject javascript via this.evaluate

[亡魂溺海] 提交于 2019-12-11 11:33:20

问题


Today I tried to inject some javascript logic into remote page using CasperJS with PhantomJS together.

Well, I'm quite surprised because of that:

casper.then(function() {
    console.log(this.evaluate(function() {
        function myMethod() {
            return 'Any thing?!';
        }
        return myMethod();
    }));
    console.log(this.evaluate(function() {
        return myMethod();
    }));
});

I tried many combinations... Like:

casper.evaluate(...)
this.evaluate(...)
casper.page.evaluate(...) <- directly to phantomJS
this.page.evaluate(...)   <- as above

First case gives me exactly what I want. But next call to evaluate act as an idiot, which never saw executed code above.

I just want to change variables, functions, and other over remote site js runtime.

Can anybody tell me why this is happening? Greetings.


回答1:


You cannot do what you are thinking. myMethod is private to the function that is passed to this.evaluate. It doesn't make sense that you would expect a private function to be available in another function, just because it was passed to the same method.

In your example, you could try

casper.then(function() {
    function myMethod() {
        return 'Any thing?!';
    }
    console.log(this.evaluate(function() {
        return myMethod();
    }));
    console.log(this.evaluate(function() {
        return myMethod();
    }));
});

But that is probably not what you are looking for? Or is it?

Or are you trying to attach code to the page itself? Maybe the following?

casper.then(function() {
    console.log(this.evaluate(function() {
        // Just creating a variable won't attach it to the window, it will
        // be local to the function. However, you can attach it to the window
        // object, which is in the scope chain
        window.myMethod = function () {return 'anything'};
    }));
    console.log(this.evaluate(function() {
        return myMethod(); // or window.myMethod();
    }));
});


来源:https://stackoverflow.com/questions/21558849/casperjs-inject-javascript-via-this-evaluate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!