I’m trying to figure out how to get the URL of the page a user was on before coming to the current one. I’m wondering if there’s a built-in JavaScript way to do this. Here’s kinda what I’m hoping for:
let lastPage = navigator.previousSite.address;
console.log('You came from: ' + lastPage);
Does anything like this exist? Or should I just save the previous URL in local storage or something? I want to use this info to make smooth transitions between pages without relying on anchor tags. Any ideas would be super helpful!
JavaScript does not offer a direct method such as navigator.previousSite.address to obtain the last visited URL. In practice, document.referrer is a common starting point, though it can return an empty string when users have entered the site directly or are coming from sources that do not pass the referrer information. I have addressed this limitation by manually saving the current URL in local storage before a page transition. This approach reliably captures the URL and allows retrieval on the next page. Depending on the project’s needs, incorporating server‐side tracking can further enhance both reliability and security.
I’ve tackled this issue before in a project. While document.referrer can work, it’s not always reliable. What I ended up doing was implementing a custom solution using the History API. Here’s a quick rundown:
On each page, I used pushState to add the current URL to the browser’s history:
history.pushState({page: window.location.href}, '', window.location.href);
Then, to get the previous URL, I used the popstate event:
window.addEventListener('popstate', function(event) {
if (event.state && event.state.page) {
console.log('Previous page:', event.state.page);
}
});
This method gave me more control and reliability than relying on document.referrer alone. It also allowed for smoother transitions between pages, which sounds like what you’re aiming for. Just remember to handle cases where there’s no previous state!
hey there! u could try using document.referrer to get the previous url. it’s not perfect tho, might not work if the user came from a bookmark or typed the url. another option is to save the current url in localstorage before leaving a page. that way u can grab it on the next page. hope this helps!