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?
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
})
You can use the javaScript history object like this history.back();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With