Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

viewportSize seems not to work with PhantomJS

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

});
like image 820
Joe Beuckman Avatar asked Nov 15 '12 02:11

Joe Beuckman


2 Answers

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();
});
like image 60
Ashish Gupta Avatar answered Sep 17 '22 12:09

Ashish Gupta


This is a known issue but I found a workaround:

  1. Load the page into an iframe of whatever size you like.
  2. Render a screenshot clipped to the rectangle of the iframe.

There is code to do it in this repository: https://github.com/jbeuckm/Splasher

like image 20
Joe Beuckman Avatar answered Sep 17 '22 12:09

Joe Beuckman