puppeteer-stream icon indicating copy to clipboard operation
puppeteer-stream copied to clipboard

Close browser causes Protocol error

Open xuhpppp opened this issue 1 year ago • 6 comments

Hi everyone, i'm using Puppeteer-stream for some recording tasks, i followed the example code on main page, everything worked fine except the case that after recording, i want to close the browser by using browser.close():

setTimeout(async () => {
		await stream.destroy();
		file.close();
                await browser.close();
		console.log("finished");
}, 1000 * 10);

but the console returned error:

this._reject(callback, new Errors_js_1.TargetCloseError('Target closed'));
                                   ^

TargetCloseError: Protocol error (Runtime.callFunctionOn): Target closed

then my application stoped. I'm running the application on Ubuntu 20.04, NodeJS 18.16.0 and Puppeteer-stream 3.0.7 Have someone ever met this issue and had the fixing way for it? Thanks for reading my issue, have a good day.

xuhpppp avatar Nov 17 '23 03:11 xuhpppp

I'm also seeing this same issue. Can't find a good way to close the process after the stream has finished writing.

dcprime avatar Nov 29 '23 19:11 dcprime

Facing same issue. @SamuelScheit Please have a look on it.

dhavalCode avatar Dec 05 '23 18:12 dhavalCode

As a workaround until I find a solution you can prevent node from crashing on errors via

process.on('uncaughtException', function (err) {
  console.error(err);
});

The error is probably caused because the stream is not properly closed, I'll investigate

samuelscheit avatar Dec 05 '23 18:12 samuelscheit

@SamuelScheit Hey, any news on this ?

saif-o99 avatar Dec 18 '23 09:12 saif-o99

The workaround that worked for me.

The most critical line is:

  • await page.evaluate((index) => window.STOP_RECORDING?.(index), i); since the extension page maintains a web socket connection and recorders that try to access a closed browser.
await stream.destroy();

await new Promise((resolve) => {
  file.close(async () => {
    const pages = await browser.pages();

    for (let i = 0; i < pages.length; i++) {
      const page = pages[i];

      // @ts-expect-error - get STOP_RECORDING from extension page.
      await page.evaluate((index) => window.STOP_RECORDING?.(index), i);

      await page.close();
    }

    await browser.close();

    wss.close(() => {
      resolve(undefined);
    });
  });
});

cc. @SamuelScheit @saif-o99 @dcprime @dhavalCode @xuhpppp

unravelers-tech avatar Jan 28 '24 01:01 unravelers-tech

@SamuelScheit Thanks for your awesome library. Did you ever find a fix for this?

farzadso avatar Jan 30 '24 11:01 farzadso