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

Viewed 1767

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?

3 Answers

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
}) 

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('/')));
}

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

Related