2016-05-15 87 views
0

我是PhantomJS和JS的新手,无法理解为什么querySelector无法访问我的元素全局变量。我试图在各种函数()中传递元素无济于事。我已经在下面包含了一个不受调用的代码副本。全局变量在page.open()内不可访问 - PhantomJS

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 

回答

3

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

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

是的,这是因为当你执行你的page.open是另一个页面上,并从以前的一个变量不与第二共享。

你将需要解决你的问题它将重新分配新页面中的参数args。

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

+0

您还可以用来打开网页的URL一起传递的值。 –

+0

是的你是对的,如果参数是值我们可以通过它在网址 –

+0

@ jeremy-denis我不知道我明白。我只是试图在page.open中重新分配参数,并没有解决问题。我也尝试过在函数()中传递元素,但也没有解决问题。 – FantasticSponge