在page.open()-PhantomJS中无法访问全局变量

Global variable not accessible inside page.open() - PhantomJS

本文关键字:访问 全局变量 -PhantomJS page open      更新时间:2023-09-26

我是PhantomJS和JS的新手,无法理解querySelector无法访问我的元素全局变量的原因。我试图在各种函数()中传递元素,但没有成功。我在下面附上了一份未经骚扰的代码副本。

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

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

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

是的,因为当你执行一个页面时,打开你的are在另一个页面上,上一个页面的变量不会与第二个页面共享。

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

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