Skip to content

Commit 5a58c02

Browse files
Normalize websocket URL in HMR to support older versions of Chrome (#19469)
1 parent 8deac8b commit 5a58c02

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/bake/client/websocket.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,25 @@ export function getMainWebSocket(): WebSocketWrapper | null {
5757
return mainWebSocket;
5858
}
5959

60+
// Modern browsers allow the WebSocket constructor to receive an http: or https: URL and implicitly convert it to a ws: or wss: URL.
61+
// But, older browsers didn't support this, so we normalize the URL manually.
62+
let normalizeWebSocketURL = (url: string) => {
63+
const origin = globalThis?.location?.origin ?? globalThis?.location?.href ?? "http://localhost:3000";
64+
let object = new URL(url, origin);
65+
if (object.protocol === "https:") {
66+
object.protocol = "wss:";
67+
} else if (object.protocol === "http:") {
68+
object.protocol = "ws:";
69+
}
70+
71+
return object.toString();
72+
};
73+
6074
export function initWebSocket(
6175
handlers: Record<number, (dv: DataView<ArrayBuffer>, ws: WebSocket) => void>,
6276
{ url = "/_bun/hmr", onStatusChange }: { url?: string; onStatusChange?: (connected: boolean) => void } = {},
6377
): WebSocketWrapper {
78+
url = normalizeWebSocketURL(url);
6479
let firstConnection = true;
6580
let closed = false;
6681

0 commit comments

Comments
 (0)