Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sveltekit

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?

like image 817
yongju lee Avatar asked Dec 05 '25 17:12

yongju lee


2 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
}) 
like image 162
yongju lee Avatar answered Dec 10 '25 08:12

yongju lee


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

like image 38
jugurtha moad Avatar answered Dec 10 '25 09:12

jugurtha moad