Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PhantomJS: getting the rendered dimensions of a page

When using PhantomJS for screen capture where most of a page's content is getting added on or during load via JavaScript, I run into a problem. Calling render() produces the correct image, showing the full content of the page, but evaluating document.body.clientHeight returns a tiny value that is presumably the page's height before any content gets added.

How can I get the height/width of the image as PhantomJS is rendering it? I don't think it's a timing issue, I've tried swapping the order of things or setting long delays to ensure everything is totally loaded.

var wp = require('webpage');

var page = wp.create();

page.viewportSize = { width: 1024, height: 768};

page.open(url, function (status) {

    if (status === 'success') {

        var f = "rendered.png";

        //Produces an image with height 4073px
        page.render(f);

        //height is only 150
        var height = page.evaluate(function() { return document.body.offsetHeight }),
            width = page.evaluate(function() { return document.body.offsetWidth });
            console.log(height,width);

    }

});
like image 689
NChase Avatar asked Sep 13 '13 12:09

NChase


1 Answers

Try using the page.onLoadFinished callback:

var wp = require('webpage');

var page = wp.create();

page.viewportSize = { width: 1024, height: 768};

page.open(url);

page.onLoadFinished = function() {
    var f = "rendered.png";

    //Produces an image with height 4073px
    page.render(f);

    //height is only 150
    var height = page.evaluate(function() { return document.body.offsetHeight }),
        width = page.evaluate(function() { return document.body.offsetWidth });
    console.log(height,width);
};

This should return the correct height and width after the page content has finished loading. I think the difference is that page.onLoadFinished waits for all content to finish loading and not just for a 200 OK response which is equivalent to the success status.

like image 82
Cameron Tinker Avatar answered Nov 08 '22 07:11

Cameron Tinker