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; }