To Use Google Cloud Function As Google Chrome

By | January 27, 2019

Google announced a couple of days ago; We can use Google Cloud Function as Chromium. For this, we use Node.js 8 runtime on Google Cloud Function. Let’s create a function on Google Cloud. Click the Create Function button.

In order, we will fill in the blanks.

  • Set a name.
  • Set the memory less 1 GB.
  • Our trigger is http.
  • I set the Source code inline.
  • You can select Python, Node.js 6 and Node.js 8. Select he Node.js 8
  • Set screenshot as the function the execute name

Then, we are writing our index.js as below.

const puppeteer = require('puppeteer');
let page;

async function getBrowserPage() {
  // Launch headless Chrome. Turn off sandbox so Chrome can run under root.
  const browser = await puppeteer.launch({args: ['--no-sandbox']});
  return browser.newPage();
}

exports.screenshot = async (req, res) => {
  const url = req.query.url;

  if (!url) {
    return res.send('Url is not found!');
  }

  if (!page) {
    page = await getBrowserPage();
  }

  await page.goto(url);
  const imageBuffer = await page.screenshot();
  res.set('Content-Type', 'image/png');
  res.send(imageBuffer);
};

After this, define the package.json.

{ 
  "name": "screenshot",
  "version": "0.0.1",
  "dependencies": { 
    "puppeteer": "^1.6.2" 
  }
}

We use the puppeteer library for this. Click the button below the form and function is created. From now on, we can trigger our url. When function is created, you will see this page.

If you click the url, you will get an error.

Right now, add a query string parameter for url. Like as below.

That’s cool. Of course, you can get fullpage or you can get title of page. You can manipulated the DOM with this way. You should check api of Puppeteer library https://github.com/GoogleChrome/puppeteer.