From 4c4976349bbdca69aa9f5d32d69debb8d4abdf87 Mon Sep 17 00:00:00 2001 From: Henrik Wenz Date: Thu, 11 Aug 2022 13:49:34 +0200 Subject: [PATCH] [example] Improve preload bridge - Enables only in devmode - Generic port --- example/main/preload.js | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/example/main/preload.js b/example/main/preload.js index 1d691f7..bd82d32 100644 --- a/example/main/preload.js +++ b/example/main/preload.js @@ -8,17 +8,23 @@ contextBridge.exposeInMainWorld("electron", { }, }); -// Patch the global WebSocket constructor to use the correct DevServer url +// Next.js Websocket DevServer is not listining on our custom scheme. +// This is why we need to monkey patch the global WebSocket constructor +// to use the correct DevServer url // More info: https://github.com/HaNdTriX/next-electron-server/issues/7 -webFrame.executeJavaScript(`Object.defineProperty(globalThis, 'WebSocket', { - value: new Proxy(WebSocket, { - construct: (Target, [url, protocols]) => { - if (url.endsWith('/_next/webpack-hmr')) { - // Fix the Next.js hmr client url - return new Target("ws://localhost:3000/_next/webpack-hmr", protocols) - } else { - return new Target(url, protocols) +if (process.env.NEXT_ELECTON_SERVER_DEV === "true") { + webFrame.executeJavaScript(`Object.defineProperty(globalThis, 'WebSocket', { + value: new Proxy(WebSocket, { + construct: (Target, [url, protocols]) => { + if (url.endsWith('/_next/webpack-hmr')) { + // Fix the Next.js hmr client url + return new Target("ws://localhost:${ + process.env.NEXT_ELECTON_SERVER_PORT || 3000 + }/_next/webpack-hmr", protocols) + } else { + return new Target(url, protocols) + } } - } - }) -});`); + }) + });`); +}