Skip to content

Commit

Permalink
Merge pull request #18 from tomcru/Fix-history-pushstate-and-replaces…
Browse files Browse the repository at this point in the history
…tate

fix: prevent redundant patching of History API methods
  • Loading branch information
tomcru authored Feb 26, 2024
2 parents e68c698 + 3b53593 commit 564d2fc
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,22 @@ const HolyLoader = ({
} catch (error) {}
};

/**
* Flag to prevent redundant patching of History API methods.
* This is essential to avoid pushState & replaceState increasingly nesting
* withing patched versions of itself
*/
let isHistoryPatched = false;

/**
* Enhances browser history methods (pushState and replaceState) to ensure that the
* progress indicator is appropriately halted when navigating through single-page applications
*/
const stopProgressOnHistoryUpdate = (): void => {
if (isHistoryPatched) {
return;
}

const originalPushState = history.pushState.bind(history);
history.pushState = (...args) => {
stopProgress();
Expand All @@ -145,6 +156,8 @@ const HolyLoader = ({
stopProgress();
originalReplaceState(...args);
};

isHistoryPatched = true;
};

/**
Expand Down Expand Up @@ -173,7 +186,6 @@ const HolyLoader = ({
}

startProgress();
stopProgressOnHistoryUpdate();
} catch (error) {
stopProgress();
}
Expand All @@ -192,6 +204,7 @@ const HolyLoader = ({
});

document.addEventListener('click', handleClick);
stopProgressOnHistoryUpdate();
} catch (error) {}

return () => {
Expand Down

0 comments on commit 564d2fc

Please sign in to comment.