1

I am new to PhantomJS and JS in general and am unable to understand why querySelector is unable to access my element global variable. I have tried to pass element within the various function()to no avail. I have included below an un-molested copy of the code.

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

Results in

$ ./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
FantasticSponge
  • 105
  • 1
  • 1
  • 9

2 Answers2

4

You can pass it by parameter (element)

var bounds = page.evaluate(function (element) { 
    canvas = document.querySelector('#'+ element);
    return canvas.getBoundingClientRect(); 
}, element);
Emilio Platzer
  • 2,327
  • 21
  • 29
1

Yes it's because when you perform a page.open your are on another page and the variable from the previous one are not shared with the second.

What you will need to solve your issue it's reassign the args variable in the new page.

But not in your case but if the variable you need to share is a value you can try passing this value in the URL to recover it in the new page.

jeremy-denis
  • 6,368
  • 3
  • 18
  • 35