question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Taking screenshot in setTimeout causes unhandledPromiseRejectionWarning

See original GitHub issue

I’m not sure if this is an issue or just something wrong that I am doing, however if I try to take a screenshot inside a setTimeout I get the error:

(node:11820) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): Error: not opened
(node:11820) [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-zero exit code.

Here is the short script I wrote to highlight the issue I’m having:

const CDP = require('chrome-remote-interface')
const fs = require('fs')

async function example() {
	try {
		var client = await CDP()
		const { Network, Page, Runtime } = client

		await Promise.all([Network.enable(), Page.enable()])
		await Page.navigate({url: 'https://www.github.com/'})
		await Page.loadEventFired()

		
		setTimeout(async () => {
			var { data } = await Page.captureScreenshot({format: 'png'})
			await fs.writeFile('test.png', data, 'base64', (err) => {
				if (err) {
					console.error(err)
				}
			})
		}, 5000)


	} catch(err) {
		console.error(err)
	} finally {
		if (client) {
			await client.close()
		}
	}
}

example()

If I add the bellow code, the more detailed error message I get is:

process.on('unhandledRejection', (reason, p) => {
	console.log('Unhandled Rejection at: Promise', p, 'reason:', reason)
})
Unhandled Rejection at: Promise Promise {
  <rejected> Error: not opened
    at WebSocket.send (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\ws\lib\WebSocket.js:355:18)
    at Chrome.enqueueCommand (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\chrome-remote-interface\lib\chrome.js:124:16)
    at C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\chrome-remote-interface\lib\chrome.js:86:28
    at Promise (<anonymous>)
    at Chrome.send (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\chrome-remote-interface\lib\chrome.js:85:16)
    at Object.handler [as captureScreenshot] (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\chrome-remote-interface\lib\api.js:32:23)
    at Timeout.setTimeout [as _onTimeout] (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\test.js:15:30)
    at ontimeout (timers.js:469:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:264:5) } reason: Error: not opened
    at WebSocket.send (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\ws\lib\WebSocket.js:355:18)
    at Chrome.enqueueCommand (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\chrome-remote-interface\lib\chrome.js:124:16)
    at C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\chrome-remote-interface\lib\chrome.js:86:28
    at Promise (<anonymous>)
    at Chrome.send (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\chrome-remote-interface\lib\chrome.js:85:16)
    at Object.handler [as captureScreenshot] (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\node_modules\chrome-remote-interface\lib\api.js:32:23)
    at Timeout.setTimeout [as _onTimeout] (C:\Users\Rowan\Documents\GitHub\StudioBookingAutomator\V3\agent\test.js:15:30)
    at ontimeout (timers.js:469:11)
    at tryOnTimeout (timers.js:304:5)
    at Timer.listOnTimeout (timers.js:264:5)

Any idea what I’m doing wrong?

Component Version
Operating system Windows 10
Node.js 8.3.0
Chrome/Chromium/… 60.0.3112.90
chrome-remote-interface 0.24.3

Is Chrome running in a container? No

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:5 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
cyrus-andcommented, Aug 17, 2017

As @Jimut says (thanks!) you’re calling Page.captureScreenshot() after client.close(), thus on a closed WebSocket. The above comment should fix your problem, but remember that exceptions inside the setTimeout are not surfaced to the parent try/catch block.

Here’s a possible solution:

const CDP = require('chrome-remote-interface');
const fs = require('fs');

async function milliseconds(n) {
    return new Promise((fulfill) => {
        setTimeout(fulfill, n);
    });
}

async function example() {
    try {
        var client = await CDP();
        const {Network, Page, Runtime} = client;

        await Promise.all([Network.enable(), Page.enable()]);
        await Page.navigate({url: 'https://www.github.com/'});
        await Page.loadEventFired();

        await milliseconds(5000);

        const {data} = await Page.captureScreenshot({format: 'png'});
        fs.writeFileSync('test.png', data, 'base64');
    } catch (err) {
        console.error(err);
    } finally {
        if (client) {
            await client.close();
        }
    }
}

example();

@Rauwomos FYI you can use node --trace-warnings to obtain the stack trace when UnhandledPromiseRejectionWarning errors happens.

1reaction
jimutcommented, Aug 17, 2017

It’s because client.close() is called before the setTimeout callback is executed.

Try this.

const CDP = require('chrome-remote-interface');
const fs = require('fs');

async function example() {
	try {
		var client = await CDP();
		const { Network, Page, Runtime } = client;

		await Promise.all([Network.enable(), Page.enable()]);
		await Page.navigate({url: 'https://www.github.com/'});
		await Page.loadEventFired();
		
		setTimeout(async () => {
			var { data } = await Page.captureScreenshot({format: 'png'});
			await fs.writeFile('test.png', data, 'base64', (err) => {
				if (err) {
					console.error(err);
				}
			});
                        client.close();
		}, 5000);
	} catch(err) {
		console.error(err);
	}
}

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

example();
Read more comments on GitHub >

github_iconTop Results From Across the Web

Cannot stop recursive setTimeout function in my react electron ...
I am working on a screen tracker app which takes screen screenshots every 10 minutes and upload it to a firebase storage. I'm...
Read more >
page.screenshot hangs if an alert() on page ready · Issue #2481
With the alert in place, you get a console log for 'loaded page' and then everything hangs indefinitely. A workaround is to use...
Read more >
Fixing UnhandledPromiseRejectionWarning in Node.js
JavaScript exhibits asynchronous behaviour for operations that are not completed immediately e.g a HTTP request or timer. These operations ...
Read more >
Node.js v19.3.0 Documentation
Using console.log() or similar asynchronous operations inside an AsyncHook callback function will cause an infinite recursion. An easy solution to this when ...
Read more >
pact-js
you define different interactions in different tests so there?s no reason why ... I'll see if i can isolate it in a smaller...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found