yongju lee
yongju lee

Reputation: 734

Going back to the previous page with 'goto' / Sveltekit navigation

I normally use the following to redirect to any page without using window.location.href in Sveltekit

import { goto } from '$app/navigation';

const goSomeWhere = () :void => {
    goto('/')
}

But how do we make it go back to the previous page? Should I just use the vanilla JavaScript to go back?

Upvotes: 17

Views: 24105

Answers (5)

OSA413
OSA413

Reputation: 486

I found a hacky solution, you can use window.history.back() and then after some time call goto(window.location.href). This triggers re-render(?) which I needed because otherwise simple window.history.back() didn't work.

window.history.back();
setTimeout(() => goto(window.location.href), 100)

Upvotes: 0

Yulian
Yulian

Reputation: 6769

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.

Upvotes: 3

yongju lee
yongju lee

Reputation: 734

You can go back to the previous page by using the afterNavigate lifecycle.

This can be more reliable than @Jarduilno's suggestion as not every incoming link is in the same parent path.

store the pathname from the from URL object, and use it later in a function. ex: goto(previousPage)

import { goto, afterNavigate } from '$app/navigation';
import { base } from '$app/paths'

let previousPage : string = base ;

afterNavigate(({from}) => {
   previousPage = from?.url.pathname || previousPage
}) 

Upvotes: 16

jugurtha moad
jugurtha moad

Reputation: 414

You can use the javaScript history object like this history.back();

Upvotes: 15

Jardulino
Jardulino

Reputation: 441

in our SvelteKit project we are sometimes navigating to previous page like in the example bellow

import { goto } from '$app/navigation';
import { page } from '$app/stores';

const goSomeWhereBack = () => {
    goto($page.url.pathname.substring(0, $page.url.pathname.lastIndexOf('/')));
}

Upvotes: 5

Related Questions