CasperJS通过this.evaluate注入javascript

时间:2014-02-04 17:06:42

标签: 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();
    }));
});

我尝试了很多组合......喜欢:

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

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

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

有人能告诉我为什么会这样吗? 问候。

1 个答案:

答案 0 :(得分: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();
    }));
});

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

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

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();
    }));
});
相关问题