How to get the previous page URL in JavaScript

You can use the document.referrer property to get the previous page URL in JavaScript. It is a read-only property that returns the URL of the document that loaded the current document.

let lastPageUrl = document.referrer
console.log(`Last visited page URL is ${lastPageUrl}`)

Note that document.referrer is not 100% accurate. Most of the time, you will get the URL of the last page the user visited if they navigated to the current page by clicking a link.

However, the value of document.referrer will be an empty string if the user navigated to the page directly by typing the URL into the address bar or using a bookmark.

Another thing that affects the value of document.referrer is rel="noreferrer" HTML attribute. This prevents passing the referrer information to the target website by removing the referral info from the HTTP header.

If you click on a link with the rel="noreferrer" HTML attribute, you won't get any referrer information on the opening page.

If you just want to go back to the previous page without knowing the URL, you could use the HTML5 History API:

history.back() // Go back to last visited page
history.forward() // Go to the next page

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.