Skip to content

Commit

Permalink
Prevent Partytown from hijacking history API (#9419)
Browse files Browse the repository at this point in the history
* Partytown overrides these methods to... do things, but it breaks ViewTransitions in Firefox.

* Only redefine pushstate/replacestate in the browser
  • Loading branch information
matthewp authored Dec 14, 2023
1 parent 242fd71 commit 151bd42
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/angry-avocados-live.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Prevent Partytown from hijacking history APIs
16 changes: 11 additions & 5 deletions packages/astro/src/transitions/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,21 @@ type State = {
};
type Events = 'astro:page-load' | 'astro:after-swap';

// Create bound versions of pushState/replaceState so that Partytown doesn't hijack them,
// which breaks Firefox.
const inBrowser = import.meta.env.SSR === false;
const pushState = (inBrowser && history.pushState.bind(history)) as typeof history.pushState;
const replaceState = (inBrowser && history.replaceState.bind(history)) as typeof history.replaceState;

// only update history entries that are managed by us
// leave other entries alone and do not accidently add state.
export const updateScrollPosition = (positions: { scrollX: number; scrollY: number }) => {
if (history.state) {
history.scrollRestoration = 'manual';
history.replaceState({ ...history.state, ...positions }, '');
replaceState({ ...history.state, ...positions }, '');
}
};
const inBrowser = import.meta.env.SSR === false;


export const supportsViewTransitions = inBrowser && !!document.startViewTransition;

Expand Down Expand Up @@ -79,7 +85,7 @@ if (inBrowser) {
} else if (transitionEnabledOnThisPage()) {
// This page is loaded from the browser addressbar or via a link from extern,
// it needs a state in the history
history.replaceState({ index: currentHistoryIndex, scrollX, scrollY }, '');
replaceState({ index: currentHistoryIndex, scrollX, scrollY }, '');
history.scrollRestoration = 'manual';
}
}
Expand Down Expand Up @@ -170,7 +176,7 @@ const moveToLocation = (to: URL, from: URL, options: Options, historyState?: Sta
if (to.href !== location.href && !historyState) {
if (options.history === 'replace') {
const current = history.state;
history.replaceState(
replaceState(
{
...options.state,
index: current.index,
Expand All @@ -181,7 +187,7 @@ const moveToLocation = (to: URL, from: URL, options: Options, historyState?: Sta
to.href
);
} else {
history.pushState(
pushState(
{ ...options.state, index: ++currentHistoryIndex, scrollX: 0, scrollY: 0 },
'',
to.href
Expand Down

0 comments on commit 151bd42

Please sign in to comment.