Skip to content

Commit

Permalink
Merge pull request #10 from mateothegreat/fix/forward-backward-naviga…
Browse files Browse the repository at this point in the history
…tion

fixed forward and backward nav
  • Loading branch information
mateothegreat authored Nov 17, 2024
2 parents 1426c04 + 61c8110 commit 3e6c9ac
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/lib/instance.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,15 +151,32 @@ export const get = (
* @param {Instance} instance The router instance to setup the history watcher for.
*/
export const setupHistoryWatcher = (instance: Instance) => {
const { pushState } = window.history;
const { pushState, replaceState } = window.history;

if (!(window.history as any)._listenersAdded) {
// Override pushState to dispatch a custom event
window.history.pushState = function (...args) {
pushState.apply(window.history, args);
window.dispatchEvent(new Event("pushState"));
};

window.addEventListener("pushState", (event: Event) => {
// Override replaceState to dispatch a custom event
window.history.replaceState = function (...args) {
replaceState.apply(window.history, args);
window.dispatchEvent(new Event("replaceState"));
};

// Listen for custom pushState and replaceState events
window.addEventListener("pushState", () => {
instance.run(get(instance, instance.routes, location.pathname));
});

window.addEventListener("replaceState", () => {
instance.run(get(instance, instance.routes, location.pathname));
});

// Listen for popstate event to detect forward and backward navigation
window.addEventListener("popstate", () => {
instance.run(get(instance, instance.routes, location.pathname));
});

Expand Down

0 comments on commit 3e6c9ac

Please sign in to comment.