Skip to content

Instantly share code, notes, and snippets.

@grav
Created June 25, 2017 18:47
Show Gist options
  • Save grav/5f4d525eef2308bf1de0d39f1439967a to your computer and use it in GitHub Desktop.
Save grav/5f4d525eef2308bf1de0d39f1439967a to your computer and use it in GitHub Desktop.
Save a dynamically rendered page with Chrome Headless browser
// Needs a running Chrome Headless, eg:
// /Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary --headless --remote-debugging-port=9222 https://chromium.org
// Run with node, eg `node render.js output.html`
const CDP = require('chrome-remote-interface');
const fs = require('fs')
CDP((client) => {
// Extract used DevTools domains.
const {Page, Runtime} = client;
// Enable events on domains we are interested in.
Promise.all([
Page.enable()
]).then(() => {
// bootstrap.html should load all js and css etc.
return Page.navigate({url: 'file://' + process.cwd() + '/render/bootstrap.html'});
});
// Evaluate outerHTML after page has loaded.
Page.loadEventFired(() => {
Runtime.evaluate({expression: 'document.documentElement.outerHTML'}).then((result) => {
fs.writeFileSync(process.argv[2],result.result.value)
client.close();
});
});
}).on('error', (err) => {
console.error('Cannot connect to browser:', err);
});
@dirkk0
Copy link

dirkk0 commented Oct 30, 2019

awesome script, thank you!

I had to fire up a local web server to get it working, but other than that, it's working great!

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