Last active
May 29, 2022 00:29
-
-
Save hinablue/da18161b503fbb0833fe637d58a70e7e to your computer and use it in GitHub Desktop.
Google Chrome headless sample code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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