PhantomJS将变量传递给page.e.evaluate以引用
问题描述:
我已经搜索了2天,但仍然没有变化,我需要foo
变量通过引用page.evaluate
内,但似乎不可能。PhantomJS将变量传递给page.e.evaluate以引用
var foo = 42;
setInterval(function(){
console.log('outer '+foo++);
},1000);
page.open(url, function() {
var pe = page.evaluate(function(foo) {
setInterval(function(){
console.log('inner inner '+foo);
},1000);
},foo);
setInterval(function(){
console.log('inner '+foo);
},1000);
}.bind(foo));
外表面和内被更新,但inner inner
foo是使用static.I还试图约束力,但返回此错误:
SyntaxError: Expected token ']'
undefined:2 in evaluateJavaScript
phantomjs://platform/webpage.js:390 in evaluate
phantomjs://code/foo.js:37
:0
phantomjs://platform/webpage.js:286 in _onPageOpenFinished
编辑: 刚刚发现的功能评价是一个沙箱,我只是好奇,如果有这样的消息传递或IPC之间的某种方式?
答
if there is some way like message passing or IPC between these two?
确实存在 - page.evaluate
可以返回一个简单的变量或序列化对象到外背景:
var value_from_sandbox = page.evaluate(function(){ return 42; });
你没有明确说明它在你的问题,但是从代码样本中我走它希望在活动页面上监视某个变量。这是可能的:
page.open(url, function() {
// Set interval function in PhantomJS scope
// that will extract a variable from the page once a second
setInterval(function(){
var foo = page.evaluate(function() {
return document.getElementById('foo').innerHTML;
}
console.log(foo);
}, 1000);
});
有叫“家”从沙箱另一种方式:page.callPhantom
,但要注意,它仍然标记为在文档中的“实验”。
我的第一个目标是实时从外部(sanbox/evaluate)发送数据到内部,这是不可能的。但在你回答的帮助下,我想我可以在'interval'块内运行整个评估并每次发送/接收数据。 – MaMadLord
它不是* enirely *不可能...您可以创建自己的事件监听器来更改页面上的数据,然后使用'page.callPhantom'发送它,但是,page.evaluate + setInterval是远远可靠的。 – Vaviloff