Skip to content

Commit 161cd17

Browse files
aleksandrebdcyrus-and
authored andcommitted
Reject current CDP commands after connection closed
Close #489
1 parent ad5f78c commit 161cd17

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

lib/chrome.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ class Chrome extends EventEmitter {
111111
this._ws.removeAllListeners('close');
112112
this._ws.once('close', () => {
113113
this._ws.removeAllListeners();
114+
this._handleConnectionClose();
114115
callback();
115116
});
116117
this._ws.close();
@@ -239,6 +240,7 @@ class Chrome extends EventEmitter {
239240
this._handleMessage(message);
240241
});
241242
this._ws.on('close', (code) => {
243+
this._handleConnectionClose();
242244
this.emit('disconnect');
243245
});
244246
this._ws.on('error', (err) => {
@@ -247,6 +249,15 @@ class Chrome extends EventEmitter {
247249
});
248250
}
249251

252+
_handleConnectionClose() {
253+
// make sure to complete all the unresolved callbacks
254+
const err = new Error('WebSocket connection closed');
255+
for (const callback of Object.values(this._callbacks)) {
256+
callback(true, err);
257+
}
258+
this._callbacks = {};
259+
}
260+
250261
// handle the messages read from the WebSocket
251262
_handleMessage(message) {
252263
// command response

test/send.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,19 @@ describe('sending a command', () => {
7979
});
8080
});
8181
});
82+
it('should catch WebSocket errors after command send', (done) => {
83+
Chrome((chrome) => {
84+
let result;
85+
chrome.Page.enable((err, res)=>{
86+
result = res;
87+
});
88+
chrome.close(()=>{
89+
assert(result instanceof Error);
90+
assert(result.message === 'WebSocket connection closed');
91+
done();
92+
});
93+
});
94+
});
8295
describe('without a callback', () => {
8396
it('should fulfill the promise if the command succeeds', (done) => {
8497
Chrome((chrome) => {

0 commit comments

Comments
 (0)