Skip to content

Commit

Permalink
Headless Chrome: keep browser alive between requests. (#675)
Browse files Browse the repository at this point in the history
Headless Chrome: keep browser alive between requests.
  • Loading branch information
steren authored and Ace Nassri committed Sep 12, 2018
1 parent d754ba6 commit 882c43f
Showing 1 changed file with 22 additions and 13 deletions.
35 changes: 22 additions & 13 deletions appengine/headless-chrome/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,32 +20,41 @@ const express = require('express');
const puppeteer = require('puppeteer');
const app = express();

let browser;

async function init () {
// [START browser]
browser = await puppeteer.launch({
args: ['--no-sandbox']
});
// [END browser]

const server = app.listen(process.env.PORT || 8080, async err => {
if (err) {
await browser.close();
return console.error(err);
}
const port = server.address().port;
console.info(`App listening on port ${port}`);
});
}

init();

app.use(async (req, res) => {
const url = req.query.url;

if (!url) {
return res.send('Please provide URL as GET parameter, for example: <a href="/?url=https://example.com">?url=https://example.com</a>');
}

// [START browser]
const browser = await puppeteer.launch({
args: ['--no-sandbox']
});
// [END browser]
const page = await browser.newPage();
let page = await browser.newPage();
await page.goto(url);
const imageBuffer = await page.screenshot();
browser.close();

res.set('Content-Type', 'image/png');
res.send(imageBuffer);
});

const server = app.listen(process.env.PORT || 8080, err => {
if (err) return console.error(err);
const port = server.address().port;
console.info(`App listening on port ${port}`);
});
// [END full_sample]

module.exports = app;

0 comments on commit 882c43f

Please sign in to comment.