0

To document my webdesign process i want to take a screenshot with a timestamp of a page on my localhost on every reload of the page or when i save the html document or the stylesheet.

i use grunt as a task runner and the headless browser phantomjs to capture the page. with grunt-localscreenshots https://www.npmjs.org/package/grunt-localscreenshots it's easy to capture the page manually. but it's cumbersome and it takes up to 10 seconds for the task to finish. the screencapture process should happen in the background, constantly but only when the page changes or is saved.

so i wrote this shellscript which monitors the directory for filechanges and fires the phantomjs-script.

while true
do
ATIME=`stat .`

if [[ "$ATIME" != "$LTIME" ]]
then
phantomjs screenshot.js
LTIME=$ATIME 
fi
sleep 0.5
done

this is the phantomjs-script

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

page.onConsoleMessage = function(msg) {
    console.log(msg);
};

page.open("http://127.0.0.1:8080/screenshot-test/dev", function(status) {
    if (status === "success") {
        window.setTimeout(function() {
            var now = Date.now();
            page.render('screenshots/' + now + '.png');
            phantom.exit();
        }, 1000);
    } else {
        console.log("nono");
        phantom.exit();
    }
});

this kinda works, but is very wonky and only fires if the html is changed. it also takes 2 or 3 duplicate screenshots if nothing actually changes, and sometimes it takes no screenshots at all. probably the reason is that the rendering of the page takes too long. any ideas for a stable and usable solution? ideal would be a grunt task

1 Answers1

0

I'd say use selenium (with phantomjs / ghostdriver). There's a python binding for it that I'm partial to, though of course Java and other languages are also supported.

You can check for page changes by taking the page_source every half a second and checking for differences. On such a change use the save_screenshot() method to save a screenshot.

Note: I've seen save_screenshot silently fail with zero-byte screenshots for truly large pages. Though even 5-10 MB screenshots are usually fine, I've repeatedly stumbled on this problem whenever I tried capturing a screenshot with a page having, let's say, hundreds of thousands of rows.

Deep-B
  • 1,342
  • 1
  • 13
  • 21