Skip to content

Commit ea0fcdc

Browse files
fix: dont try to close not closed cdp ws
1 parent d470fe9 commit ea0fcdc

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

src/browser/cdp/connection.ts

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,18 @@ enum WsConnectionStatus {
2828

2929
type OnEventMessageFn = (cdpEventMessage: CDPEvent) => unknown;
3030

31+
// Closing WS when its still not connected produces error:
32+
// https://github.com/websockets/ws/blob/86eac5b44ac2bff9087ec40c9bd06bc7b4f0da07/lib/websocket.js#L297-L301
33+
const closeWsConnection = (ws: WebSocket): void => {
34+
if (ws.readyState !== ws.CONNECTING) {
35+
ws.close();
36+
} else {
37+
ws.once("open", () => {
38+
ws.close();
39+
});
40+
}
41+
};
42+
3143
export class CDPConnection {
3244
public onEventMessage: OnEventMessageFn | null = null;
3345
private readonly _cdpWsEndpoint: string;
@@ -80,7 +92,7 @@ export class CDPConnection {
8092
let isSettled = false;
8193

8294
const timeoutId = setTimeout(() => {
83-
ws.close();
95+
closeWsConnection(ws);
8496
done(
8597
new CDPTimeoutError({
8698
message: `Couldn't establish CDP connection to "${endpoint}" in ${CDP_CONNECTION_TIMEOUT}ms`,
@@ -93,7 +105,7 @@ export class CDPConnection {
93105
};
94106

95107
const onError = (error: unknown): void => {
96-
ws.close();
108+
closeWsConnection(ws);
97109
done(
98110
new CDPError({
99111
message: `Couldn't establish CDP connection to "${endpoint}": ${error}`,
@@ -165,7 +177,7 @@ export class CDPConnection {
165177

166178
if (this._wsConnectionStatus === WsConnectionStatus.CLOSED) {
167179
if (result instanceof WebSocket) {
168-
result.close();
180+
closeWsConnection(result);
169181
}
170182
throw new CDPConnectionTerminatedError();
171183
}
@@ -444,7 +456,7 @@ export class CDPConnection {
444456
this._abortPendingRequests(`Request was aborted because ${sessionAbortMessage}`);
445457
this._pingHealthCheckStop();
446458

447-
ws.close();
459+
closeWsConnection(ws);
448460
}
449461

450462
/**

0 commit comments

Comments
 (0)