How to get the previous URL in JavaScript?

document.referrer

in many cases will get you the URL of the last page the user visited, if they got to the current page by clicking a link (versus typing directly into the address bar, or I believe in some cases, by submitting a form?). Specified by DOM Level 2. More here.

window.history allows navigation, but not access to URLs in the session for security and privacy reasons. If more detailed URL history was available, then every site you visit could see all the other sites you’d been to.

If you’re dealing with state moving around your own site, then it’s possibly less fragile and certainly more useful to use one of the normal session management techniques: cookie data, URL params, or server side session info.

Leave a Comment