Skip to content

Commit

Permalink
fix: prevent redundant patching of History API methods
Browse files Browse the repository at this point in the history
The previous implementation of patching the History API methods (pushState and replaceState) was causing them to increasingly nest within patched versions of themselves.

To fix this, a new flag `isHistoryPatched` was introduced to prevent redundant patching. The `stopProgressOnHistoryUpdate` function now checks if the flag is already set before applying the patch. Additionally, the flag is set to `true` after the patching is done to ensure it is only applied once.

Reference: TheSGJ/nextjs-toploader#68
  • Loading branch information
tomcru committed Feb 26, 2024
1 parent e68c698 commit 820bd33
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -128,23 +128,36 @@ 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();
originalPushState(...args);
originalPushState.apply(history, args);
};

// This is crucial for Next.js Link components using the 'replace' prop.
const originalReplaceState = history.replaceState.bind(history);
history.replaceState = (...args) => {
stopProgress();
originalReplaceState(...args);
originalReplaceState.apply(history, 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 820bd33

Please sign in to comment.