CasperJS通过this.evaluate注入javascript

The*_*ler 1 javascript phantomjs casperjs

今天我尝试使用CasperJS和PhantomJS一起向远程页面注入一些javascript逻辑.

嗯,我很惊讶因为:

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

我试过很多组合...喜欢:

casper.evaluate(...)
this.evaluate(...)
casper.page.evaluate(...) <- directly to phantomJS
this.page.evaluate(...)   <- as above
Run Code Online (Sandbox Code Playgroud)

第一个案例给了我我想要的东西.但接下来要求评估作为一个白痴,从未见过上面执行过的代码.

我只想更改变量,函数和其他远程站点js运行时.

任何人都可以告诉我为什么会这样吗?问候.

Jua*_*des 5

你不能做你想的.myMethod是传递给函数的私有this.evaluate.你期望私有函数在另一个函数中可用是没有意义的,因为它被传递给了同一个方法.

在您的示例中,您可以尝试

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

但这可能不是你想要的?或者是吗?

或者您是否尝试将代码附加到页面本身?也许以下?

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();
    }));
});
Run Code Online (Sandbox Code Playgroud)