Skip to content

Commit 820bd33

Browse files
committed
fix: prevent redundant patching of History API methods
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
1 parent e68c698 commit 820bd33

File tree

1 file changed

+16
-3
lines changed

1 file changed

+16
-3
lines changed

src/index.tsx

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -128,23 +128,36 @@ const HolyLoader = ({
128128
} catch (error) {}
129129
};
130130

131+
/**
132+
* Flag to prevent redundant patching of History API methods.
133+
* This is essential to avoid pushState & replaceState increasingly nesting
134+
* withing patched versions of itself
135+
*/
136+
let isHistoryPatched = false;
137+
131138
/**
132139
* Enhances browser history methods (pushState and replaceState) to ensure that the
133140
* progress indicator is appropriately halted when navigating through single-page applications
134141
*/
135142
const stopProgressOnHistoryUpdate = (): void => {
143+
if (isHistoryPatched) {
144+
return;
145+
}
146+
136147
const originalPushState = history.pushState.bind(history);
137148
history.pushState = (...args) => {
138149
stopProgress();
139-
originalPushState(...args);
150+
originalPushState.apply(history, args);
140151
};
141152

142153
// This is crucial for Next.js Link components using the 'replace' prop.
143154
const originalReplaceState = history.replaceState.bind(history);
144155
history.replaceState = (...args) => {
145156
stopProgress();
146-
originalReplaceState(...args);
157+
originalReplaceState.apply(history, args);
147158
};
159+
160+
isHistoryPatched = true;
148161
};
149162

150163
/**
@@ -173,7 +186,6 @@ const HolyLoader = ({
173186
}
174187

175188
startProgress();
176-
stopProgressOnHistoryUpdate();
177189
} catch (error) {
178190
stopProgress();
179191
}
@@ -192,6 +204,7 @@ const HolyLoader = ({
192204
});
193205

194206
document.addEventListener('click', handleClick);
207+
stopProgressOnHistoryUpdate();
195208
} catch (error) {}
196209

197210
return () => {

0 commit comments

Comments
 (0)