Diego Ulloa
Diego Ulloa

Reputation: 639

Sveltekit: Get last visited route

I've been trying to get the last visited route, after googling for long time I'm not able to find anything, it looks like is not so simple as it sounds, is it?

What I want is to store the last visited route in a state all of this in order to preload data from ssr when pressing a go back button.

This is an error page so idk from what page the user is coming.

I'm using sveltekit 2.

<button
  on:click={() => goto('previous-route-here')}
  on:mouseenter={async () => await preloadData('previous-route-here')}
>
  Go Back
</botton>

Upvotes: 0

Views: 698

Answers (1)

archoda
archoda

Reputation: 71

There are a few options:

  1. If you're just utilizing your own link/urls and none from the outside world ( since a link w/ rel=noreferrer would be empty ), you could use the document.referrer
const previousURL = document.referrer;
  1. You can use the history api, but might not be best option dependant on your navigation model history.back();

  2. Alternative route is to use a simple svelte $store ( or localstorage or cookie object ) that records route in your +layout.svelte then use that.

window.addEventListener('popstate', function(event) {
console.log( event?.state?.previousURL ?? 'No referrer URL');
});

Upvotes: 1

Related Questions