![](/img/trans.png)
[英]CasperJS click google search button, this.evaluate() javascript
[英]CasperJS inject javascript via this.evaluate
今天,我尝试将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运行时更改变量,函数及其他。
谁能告诉我为什么会这样吗? 问候。
你不能做你想的。 myMethod
对传递给this.evaluate
的函数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();
}));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.