viewportSize seems not to work with PhantomJS

Joe Beuckman picture Joe Beuckman · Nov 15, 2012 · Viewed 14.1k times · Source

Shouldn't the output from this PhantomJS script be 240x320 pixels? I'm getting a large, default-sized image. clipRect() would seem to render the correct size image, but I need the responsive content of the page to reflect the actual browser window size.

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

page.viewportSize = { width: 240, height: 320 };  

page.open('http://cnn.com', function (status) {

    if (status !== 'success') {
        console.log('Unable to load the address!');
    } else {
        window.setTimeout(function () {
            page.render('default.png');
            phantom.exit();
        }, 200);
    }

});

Answer

Ashish Gupta picture Ashish Gupta · Oct 1, 2014

This works!! Found the snippet on the github page of the issue.It forces the 'body' element to the page viewportSize:

var width = 1024;
var height = 768;
var webpage = require('webpage');

page = webpage.create();
page.viewportSize = {width: width, height: height};
page.open('http://harness.io', function(status) {
    console.log(status);
    page.evaluate(function(w, h) {
      document.body.style.width = w + "px";
      document.body.style.height = h + "px";
    }, width, height);
    page.clipRect = {top: 0, left: 0, width: width, height: height};                                                                                                                           
    page.render('/tmp/test.png');
    phantom.exit();
});