Adventures in Screenshotting

I’m having one of those mornings, where nothing works quite right. I managed to get a screenshot to work, but couldn’t get it to resize to a narrow, “mobile phone” width.

This is what half-worked in PhantomJS.

var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = {
    width: 1920,
    height: 1080
};
page.scrollPosition = {
    top: 1,
    left: 0
};
page.open('http://example.com/', function() {
    console.log('fetched');
    window.setTimeout(function() {
        console.log('saving screenshot');
        page.render('koya.png');

        page = webPage.create();
        page.viewportSize = {
            width: 320,
            height: 480
        };
        page.open('http://example.com/', function() {
            console.log('fetched');
            window.setTimeout(function() {
                console.log('saving');
                page.render('koya-m.png');
                phantom.exit();
            }, 3000);
            window.setInterval(function () {}, 100);
        });
    }, 2000);
});

It would not shrink the window width.

So I turned to Selenium. This code is already a little obsolete – I think the library will save files for you. It worked. It was just a little hard to find the instructions to do this, and I found it by searching for “resize” in the GitHub repo.

var fs = require('fs');
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().forBrowser('firefox').build();

driver.get('http://example.com/');
driver.manage().window().setSize(1920,1080);
saveScreenshot('koya-d.png');
driver.manage().window().setSize(400,800);
saveScreenshot('koya-m.png');

function saveScreenshot(name) {
    driver.takeScreenshot().then(function(data){
        var base64Data = data.replace(/^data:image/png;base64,/,"");
        fs.writeFile(name, base64Data, 'base64', function(err) {
            if(err) console.log(err);
        });
    });
}