Home >Web Front-end >JS Tutorial >How Can I Reliably Get the Previous URL in JavaScript?
In JavaScript, obtaining the previous URL visited by a user can be tricky. However, several approaches can be employed.
Using document.referrer:
The document.referrer property provides the URL of the previous page if the user navigated to the current page via a hyperlink. It can be obtained as follows:
console.log("Previous URL: " + document.referrer);
Limitations of document.referrer:
History Management with window.history:
window.history allows for manipulating the browser's history, but does not directly provide access to URLs. However, the history.state object can be used to store a custom URL property:
history.state = { prevUrl: location.href };
Then, you can retrieve it in the previous page:
const prevUrl = history.state && history.state.prevUrl;
Other Approaches:
Security Considerations:
Providing access to the previous URL raises security and privacy concerns, as it could allow malicious websites to track user browsing history. Therefore, browsers have implemented restrictions on URL accessibility.
The above is the detailed content of How Can I Reliably Get the Previous URL in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!