crazy4groovy
8/18/2017 - 3:19 AM

A simple puppeteer (headless Chrome) nodejs script example

A simple puppeteer (headless Chrome) nodejs script example

const puppeteer = require('puppeteer');

(async() => {
  const browser = await puppeteer.launch();

  try {
    const page = await browser.newPage();
    await page.emulate({
      userAgent: 'Headless-Chrome',
      viewport: {
        width: 1800,
        height: 1024,
      }
    })
    await page.goto('https://google.com');
    await page.screenshot({
      path: './screens/example-' + Date.now() + '.png'
    });

    const answereToAll = 42;
    page.on('dialog', dialog => {
      console.log(dialog.message(), answereToAll);
      dialog.dismiss();
    });
    const res1 = await page.evaluate((a) => {
      alert(Math.random());
      return Promise.resolve(a + 1);
    }, answereToAll);

    console.log(res1);
  } catch (err) {
    console.error('ERROR:', err.message);
  } finally {
    console.log('FINISHED');
  }

  await browser.close();
})();