How to get the previous URL in JavaScript?
Fetch the prior URL using the document.referrer
method:
The returned string is empty if no referrer is available or due to privacy policies.
Understanding the value of document.referrer
While using document.referrer
seems simple, its value may not always be reliable. Cross-domain navigations, direct URL entries, and bookmarks won't generate any referrer. However, within site navigation, it works well for providing the URL of the page visited before the current one.
Overcoming limitations of document.referrer
Ways to track the previous URL
When document.referrer
proves inadequate, consider these methods:
- URL parameters: Use query strings to include a previous page indicator when navigating.
- Cookies: Store the current URL before navigating, to be referred to as the "previous" URL on the next load.
- Session Storage: Think about using
sessionStorage
orlocalStorage
for better state management. - Server-side sessions: Keep the prior URL in your server's session state, ready for retrieval during the next request.
Working with the window.history object
The History API provides history.pushState
, history.back()
, history.forward()
, and history.go()
to adjust and navigate the browser history. However, take note that these methods don't return the previous URL; they navigate to it instead.
Caveats and implications
Privacy matters
Remember to always place user privacy at the forefront when you're trying to track navigation histories. Always seek user consent if you're storing their navigational data through cookies or similar methods.
Security hazards
Avoiding cross-site scripting (XSS) vulnerabilities when processing URLs is vital. Sanitise any information if you plan to display it or use it for further processing.
Known limitations and inconsistencies
Intra-frame navigation
document.referrer
can behave unpredictably with iframes or framesets. Each frame may retain its own referrer information, which could be inconsistent with the top-level document's URL.
Browser incoherence
Some browsers and configurations may modify or omit referrer information, so cross-browser testing and being aware of privacy settings is paramount.
Making use of the HTML5 History API
Applying pushState for SPAs
Single-Page Applications (SPAs) often leverage history.pushState
and window.history.state
to manage state transitions smoothly without page reloads. This can also store the previous URL in a state object:
Compatibility matters
Always check browser compatibility for pushState
and related functions as older browsers might not support these features.
Was this article helpful?