Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnhandledPromiseRejectionWarning when running Puppeteer?

Why do I get the following warnings, and how can I get rid of them?

Warnings:

(node:26771) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Protocol error (Runtime.callFunctionOn): Target closed.

(node:26771) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zeroexit code.

Code:

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto("https://dn.se", { waitUntil: "domcontentloaded" });
    var output = page.evaluate(() => {
        return;
    });
    await browser.close();
})();

Environment:

  • macOS High Sierra
  • Node v8.5.0
  • Puppeteer: 1.9.0
like image 480
user1283776 Avatar asked Dec 10 '25 17:12

user1283776


1 Answers

You need to await page.evaluate(), as it returns a promise:

var output = await page.evaluate(() => {
  return;
});

Make sure you are using process.on('unhandledRejection') to listen for unhandled promise rejections and to gracefully close the browser if such an event should occur:

process.on('unhandledRejection', (reason, p) => {
  console.error('Unhandled Rejection at: Promise', p, 'reason:', reason);
  browser.close();
});

Your final code should end up looking like this:

'use strict';

const puppeteer = require('puppeteer');

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

  process.on('unhandledRejection', (reason, p) => {
    console.error('Unhandled Rejection at: Promise', p, 'reason:', reason);
    browser.close();
  });

  await page.goto('https://dn.se', {
    waitUntil: 'domcontentloaded',
  });

  var output = await page.evaluate(() => {
    return;
  });

  await browser.close();
})();
like image 139
Grant Miller Avatar answered Dec 12 '25 05:12

Grant Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!