Skip to content

Instantly share code, notes, and snippets.

@taveras
Last active October 11, 2016 03:22
Show Gist options
  • Save taveras/018698be17d23a5bfa7fe827702fa172 to your computer and use it in GitHub Desktop.
Save taveras/018698be17d23a5bfa7fe827702fa172 to your computer and use it in GitHub Desktop.
mimics Google Search Console's fetch and render, using Nightmare.js
var argv = process.argv.slice(2);
var urlToTest = argv[0];
var screenshotFilename = argv[1];
if (!screenshotFilename) {
throw new Error('Invalid screenshot path.')
}
if (!urlToTest) {
throw new Error('Invalid URL to test.')
}
var PAGE_WIDTH = 1200;
var PAGE_HEIGHT = 10000;
var RENDER_DELAY = 5000;
var pathForScreenshot = require('path').join(__dirname, screenshotFilename);
var Nightmare = require('nightmare');
var nightmare = Nightmare({
show: false, // this option must be false, otherwise the viewport will not be valid
waitTimeout: RENDER_DELAY * 2,
goToTimeout: RENDER_DELAY,
webPreferences: {
width: PAGE_WIDTH,
height: PAGE_HEIGHT
}
});
function getSEOMeta() {
var h1s = [];
document.querySelectorAll('h1').forEach(function (el) {
h1s.push(el.textContent.trim());
});
return {
title: document.querySelector('head title').textContent,
h1: h1s
};
}
function printSEOMeta(result) {
console.log('title: ' + result.title);
result.h1.forEach(function (el) {
console.log('h1: ' + el);
});
}
nightmare
.viewport(PAGE_WIDTH, PAGE_HEIGHT)
.goto(urlToTest)
.wait(RENDER_DELAY)
.screenshot(pathForScreenshot)
.evaluate(getSEOMeta)
.end()
.then(printSEOMeta)
.catch(function (error) {
console.error('Fetch and render failed: ', error);
});
@taveras
Copy link
Author

taveras commented Oct 10, 2016

usage:

$ node fetch-and-render.js http://www.self.com/story/classic-denim screenshot.png

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment