From 82bad5d6205672ed3f6a49d4de53d3a68367433e Mon Sep 17 00:00:00 2001 From: Martin Trapp <94928215+martrapp@users.noreply.github.com> Date: Thu, 4 Jan 2024 12:15:35 +0100 Subject: [PATCH] Fixes page titles in the browser's drop-down for back / forward navigation when using view transitions (#9586) * Fixes titles in the browser's dropdown for back / forwards traversals through the browser history * Improve names of constants * Reword the changset description --- .changeset/silent-rabbits-cross.md | 5 +++++ packages/astro/src/transitions/router.ts | 17 ++++++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) create mode 100644 .changeset/silent-rabbits-cross.md diff --git a/.changeset/silent-rabbits-cross.md b/.changeset/silent-rabbits-cross.md new file mode 100644 index 000000000000..d00b47f4f10f --- /dev/null +++ b/.changeset/silent-rabbits-cross.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +Fixes page titles in the browser's drop-down for back / forward navigation when using view transitions diff --git a/packages/astro/src/transitions/router.ts b/packages/astro/src/transitions/router.ts index 5d07287b6f00..41b9acf874d1 100644 --- a/packages/astro/src/transitions/router.ts +++ b/packages/astro/src/transitions/router.ts @@ -170,9 +170,18 @@ function runScripts() { // Add a new entry to the browser history. This also sets the new page in the browser addressbar. // Sets the scroll position according to the hash fragment of the new location. -const moveToLocation = (to: URL, from: URL, options: Options, historyState?: State) => { +const moveToLocation = ( + to: URL, + from: URL, + options: Options, + pageTitleForBrowserHistory: string, + historyState?: State +) => { const intraPage = samePage(from, to); + const targetPageTitle = document.title; + document.title = pageTitleForBrowserHistory; + let scrolledToTop = false; if (to.href !== location.href && !historyState) { if (options.history === 'replace') { @@ -223,6 +232,7 @@ const moveToLocation = (to: URL, from: URL, options: Options, historyState?: Sta } history.scrollRestoration = 'manual'; } + document.title = targetPageTitle; }; function preloadStyleLinks(newDocument: Document) { @@ -409,8 +419,9 @@ async function updateDOM( throw new DOMException('Transition was skipped'); } + const pageTitleForBrowserHistory = document.title; // document.title will be overridden by swap() const swapEvent = await doSwap(preparationEvent, viewTransition!, defaultSwap); - moveToLocation(swapEvent.to, swapEvent.from, options, historyState); + moveToLocation(swapEvent.to, swapEvent.from, options, pageTitleForBrowserHistory, historyState); triggerEvent(TRANSITION_AFTER_SWAP); if (fallback === 'animate' && !skipTransition) { @@ -441,7 +452,7 @@ async function transition( updateScrollPosition({ scrollX, scrollY }); } if (samePage(from, to) && !!to.hash) { - moveToLocation(to, from, options, historyState); + moveToLocation(to, from, options, document.title, historyState); return; }