You can made use of the navigating store from $app/stores.
import { navigating } from "$app/stores";
export const previousPage = readable(null, (set) => {
const unsubscribe = navigating.subscribe(($navigating) => {
// Check if `$navigating` has a value
// because it's set to `null` after navigation is done
if ($navigating) {
set($navigating.from.url.pathname);
}
});
return () => unsubscribe();
});
Keep in mind that this store is keeping track of the previously opened page and is not a stack. So calling goto($previousPage) multiple times one after the other will get you stuck in a loop.
Alternatively, if you want to use the History API instead (which uses a stack), you can just call history.back() as mentioned in this answer.