【问题标题】:Global variable not accessible inside page.open() - PhantomJS [duplicate]page.open()内部无法访问全局变量 - PhantomJS [重复]
【发布时间】:2016-05-15 17:53:37
【问题描述】:

我通常是 PhantomJS 和 JS 的新手,无法理解为什么 querySelector 无法访问我的元素全局变量。我试图在各种 function() 中传递元素但无济于事。我在下面包含了一份未经篡改的代码副本。

var page = require('webpage').create();
var args = require('system').args;

var uri = args[1];
var element  = args[2];

console.log('Arg 1: '+args[1]);
console.log('Arg 2: '+args[2]);

page.open(uri, function (status) {
    if (status !== 'success') {
        console.log('Error Opening Page');
    } else {
        window.setTimeout(function () {
            var bounds = page.evaluate(function () { 

        canvas = document.querySelector('#'+ element);

        return canvas.getBoundingClientRect(); 
            });

            page.clipRect = {
                top:    bounds.top,
                left:   bounds.left,
                width:  bounds.width,
                height: bounds.height
            };

            page.render('result.png');
            phantom.exit();
        }, 500);
    }
});

结果

$ ./phantomjs test.js http://fabricjs.com/static_canvas c
Arg 1: http://fabricjs.com/static_canvas
Arg 2: c
ReferenceError: Can't find variable: args

  undefined:3
  :6
TypeError: null is not an object (evaluating 'bounds.top')

  phantomjs://code/test.js:23

【问题讨论】:

    标签: javascript phantomjs parameter-passing


    【解决方案1】:

    可以通过参数(元素)传递

    var bounds = page.evaluate(function (element) { 
        canvas = document.querySelector('#'+ element);
        return canvas.getBoundingClientRect(); 
    }, element);
    

    【讨论】:

      【解决方案2】:

      是的,这是因为当您执行 page.open 时,您是在另一个页面上,并且前一个页面中的变量不会与第二个页面共享。

      解决问题所需的方法是在新页面中重新分配 args 变量。

      但不是你的情况,但如果你需要共享的变量是一个值,你可以尝试在 URL 中传递这个值以在新页面中恢复它。

      【讨论】:

      • 您还可以将值与用于打开页面的 URL 一起传递。
      • 是的,如果参数是值,我们可以在 URL 中传递它是对的
      • @jeremy-denis 我不确定我是否理解。我只是尝试在 page.open 中重新分配 args,但这并没有解决问题。我也尝试过在 function() 中传递元素,但这也没有解决问题。
      • 你能检查一下 require('system').args 是否在你的页面中返回了一些东西吗?
      • args 实际上在 page.open() 的范围内可见,只是不在页面的评估范围内。 Emilio 的解决方案奏效了。
      猜你喜欢
      • 1970-01-01
      • 2011-07-23
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 2014-01-17
      相关资源
      最近更新 更多