Sudo Sur
Sudo Sur

Reputation: 611

Close Browser after Navigation Timeout

I have this code below made with nodejs + puppeteer, whose goal is to take a screenshot of the user's site:

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://MY_WEBSITE/try/slowURL',{timeout: 30000, waitUntil: 'networkidle0' });//timeout 30 seconds
await page.setViewport({width: 1920, height: 1080});
await page.screenshot({path: pathUpload});
await browser.close();

Its operation is quite simple, but to test the timeout I created a page (http://MY_WEBSITE/try/slowURL) that takes 200 seconds to load.

According to the puppeteer timeout (timeout: 30000), there is a 100% chance of a Navigation Timeout Exceeded: 30000ms exceeded error happening, especially because I'm forcing it.

THE PROBLEM

Through the htop command (used in linux), even after the system crashes and shows "TimeoutError", I can see that the browser has not been closed.

And if the browser is not closed, as scans were done, there is a good chance that the server will run out of memory, and I don't want that.

How can I solve this problem?

Upvotes: 4

Views: 1928

Answers (1)

Thomas Dondorf
Thomas Dondorf

Reputation: 25240

You want to wrap your code into a try..catch..finally statement to handle the error and close the browser.

Code Sample

const browser = await puppeteer.launch();
try {
    const page = await browser.newPage();
    await page.goto(/* ... */);
    // more code which might throw...
} catch (err) {
    console.error('error', err.message);
} finally {
    await browser.close();
}

Your main code is executed inside a try block. The catch block shows any kind of error that might happened. The finally part is the part of your script that is always executed, not only when an error is thrown. That way, independent of whether an error happened or not, your script will call the browser.close function.

Upvotes: 7

Related Questions