Skip to content

Commit 564d2fc

Browse files
authored
Merge pull request #18 from tomcru/Fix-history-pushstate-and-replacestate
fix: prevent redundant patching of History API methods
2 parents e68c698 + 3b53593 commit 564d2fc

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

src/index.tsx

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,11 +128,22 @@ 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();
@@ -145,6 +156,8 @@ const HolyLoader = ({
145156
stopProgress();
146157
originalReplaceState(...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)