From 937d4c9da665b22d286f1b7c274a8c9535beb030 Mon Sep 17 00:00:00 2001 From: Safia Abdalla Date: Mon, 18 Sep 2023 11:54:29 -0700 Subject: [PATCH] Trigger enhanced page nav on hot reload (#35450) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Depends on https://github.com/dotnet/aspnetcore/pull/50437. Addresses https://github.com/dotnet/aspnetcore/issues/49144. | Scenario | Validated | |---|---| | Statically server rendered page | ✅ | | Interactive server rendered page | ✅ | | Page with stream rendering enabled | ✅ | | Interactive client rendered page | ❌ (https://github.com/dotnet/aspnetcore/issues/50765) | | Statically server rendered page with interactive components (all render modes) | ✅ | --- .../WebSocketScriptInjection.js | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/BuiltInTools/BrowserRefresh/WebSocketScriptInjection.js b/src/BuiltInTools/BrowserRefresh/WebSocketScriptInjection.js index 7e9888999d76..fe099ec00862 100644 --- a/src/BuiltInTools/BrowserRefresh/WebSocketScriptInjection.js +++ b/src/BuiltInTools/BrowserRefresh/WebSocketScriptInjection.js @@ -1,4 +1,5 @@ setTimeout(async function () { + const hotReloadActiveKey = '_dotnet_watch_hot_reload_active'; // Ensure we only try to connect once, even if the script is both injected and manually inserted const scriptInjectedSentinel = '_dotnet_watch_ws_injected'; if (window.hasOwnProperty(scriptInjectedSentinel)) { @@ -181,18 +182,33 @@ setTimeout(async function () { if (document.querySelector('#dotnet-hotreload-toast')) { return; } + if (!window[hotReloadActiveKey]) + { + return; + } const el = document.createElement('div'); el.id = 'dotnet-hotreload-toast'; el.innerHTML = ""; el.setAttribute('style', 'z-index: 1000000; width: 48px; height: 48px; position:fixed; top:5px; left: 5px'); document.body.appendChild(el); + window[hotReloadActiveKey] = false; setTimeout(() => el.remove(), 2000); } function aspnetCoreHotReloadApplied() { if (window.Blazor) { - // If this page has any Blazor, don't refresh the browser. - notifyHotReloadApplied(); + window[hotReloadActiveKey] = true; + // hotReloadApplied triggers an enhanced navigation to + // refresh pages that have been statically rendered with + // Blazor SSR. + if (window.Blazor?._internal?.hotReloadApplied) + { + Blazor._internal.hotReloadApplied(); + } + else + { + notifyHotReloadApplied(); + } } else { location.reload(); } @@ -274,6 +290,8 @@ setTimeout(async function () { webSocket.addEventListener('open', onOpen); webSocket.addEventListener('close', onClose); + webSocket.addEventListener('close', () => window.Blazor?.removeEventListener('enhancedload', notifyHotReloadApplied)); + window.Blazor?.addEventListener('enhancedload', notifyHotReloadApplied); }); } }, 500);