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.