PhantomJS 通过引用将变量传递给 page.evaluate

PhantomJS Passing variable to page.evaluate by reference

我已经搜索了 2 天,但仍然没有任何变化,我需要在 page.evaluate 中引用 foo 变量,但似乎不可能。

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 也尝试绑定但是它 returns 这个错误:

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

编辑: 刚刚发现函数 evaluate 是一个沙箱,我很好奇这两者之间是否有某种方式,如消息传递或 IPC?

if there is some way like message passing or IPC between these two?

确实有 - page.evaluate 可以 return 一个简单的变量或序列化对象到外部上下文:

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

});

还有一种从沙盒中调用 "home" 的方法:page.callPhantom,但请注意它在文档中仍被标记为 "experimental"。