Instantly share code, notes, and snippets.

@hinablue /server.js
Last active May 25, 2017

Embed
What would you like to do?
Google Chrome headless sample code
const http = require('http')
const Koa = require('koa')
const CDP = require('chrome-remote-interface')
const PORT = process.argv[2] || 3000
const ADDRESS = process.argv[3] || '0.0.0.0'
const app = new Koa()
app.use(async (ctx, next) => {
const URL = ctx.request.url.substr(1)
await next()
CDP((client) => {
const { Network, Page, Runtime } = client
Network.requestWillBeSent(params => params.request.url)
Page.loadEventFired(() => {
console.log('Page loaded.')
setTimeout(() => {
Runtime.evaluate({expression: 'document.documentElement.outerHTML'}).then(result => {
console.log('Page evaluate succeeded.')
ctx.body = '<!DOCTYPE html>' + result.result.value
})
client.close()
}, 3000)
})
Promise.all([Network.enable(), Page.enable()])
.then(() => {
return Page.navigate({ url: URL })
}).catch((err) => {
console.error(err)
client.close()
})
}).on('error', (err) => {
console.error('CDP ERROR.', err)
ctx.body = '<html></html>'
})
})
http.createServer(app.callback()).listen(PORT, ADDRESS, () => {
console.log('Starting prerender server on http://%s:%s', ADDRESS, PORT)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment