Home >Web Front-end >JS Tutorial >How Can I Reliably Get the Previous URL in JavaScript?

How Can I Reliably Get the Previous URL in JavaScript?

DDD
DDDOriginal
2024-11-28 12:59:11321browse

How Can I Reliably Get the Previous URL in JavaScript?

Determining 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:

  • It is unreliable if the user types the URL directly into the address bar or submits a form.
  • It is not accessible in some security-conscious browsers, such as Safari.

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:

  • Cookies: Setting a cookie to store the previous URL is a viable option, but requires extra server-side logic.
  • Parameter Tracking: Append a parameter to the current URL containing the previous URL, but this method can clutter the URL if the user navigates frequently.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn