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

How Can I Get the Referrer URL in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-30 04:48:10634browse

How Can I Get the Referrer URL in JavaScript?

Retrieving the Previous URL in JavaScript

Wondering how to access the URL of the page that preceded the current one in JavaScript? While the method you described using window.history.previous.href is not available, there is an alternative solution:

Use document.referrer: This property contains the URL of the page from which the current page was accessed. It is widely supported in browsers and reliable in many cases where the user navigated to the current page by clicking a link.

alert("Previous URL is: " + document.referrer);

Note that document.referrer may not be available in certain scenarios, such as direct URL input or form submissions. Additionally, it may not accurately reflect the previous URL if the user accessed the current page through a bookmark or cached history.

Limitations and Considerations

For enhanced security and privacy, JavaScript does not have direct access to the full URL history of the browser. This prevents websites from tracking the entirety of a user's browsing activity.

If you are managing application state within your own site, consider using session management techniques like cookies, URL parameters, or server-side session storage instead. These methods provide a more reliable and structured approach to maintaining state across page transitions.

The above is the detailed content of How Can I Get the Referrer 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