CasperJS通过this.evaluate注入javascript [英] CasperJS inject javascript via this.evaluate

查看:148
本文介绍了CasperJS通过this.evaluate注入javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

好吧,因此我很惊讶:

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.

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

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

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

Can anybody tell me why this is happening? Greetings.

推荐答案

您无法做自己想做的事情. myMethod是传递给this.evaluate的函数的专用.仅仅因为将一个私有函数传递给了相同的方法,就不会期望它在另一个函数中可用.

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

这篇关于CasperJS通过this.evaluate注入javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆