Keywords: JavaScript | document.referrer | page navigation | URL retrieval | web development
Abstract: This article provides an in-depth exploration of various methods to obtain the previous page URL in JavaScript, with detailed analysis of the document.referrer property's functionality, use cases, and limitations. Through comprehensive code examples and practical scenarios, it demonstrates proper usage of this property for retrieving referral information while addressing security constraints and alternative approaches. The guide also covers relevant history API methods to offer complete solutions for developers.
Introduction
In modern web development, obtaining the URL of the user's previously visited page is a common requirement, particularly for implementing page navigation, user behavior tracking, or state management. JavaScript offers multiple approaches to address this need, with the document.referrer property being the most direct and widely used method.
Fundamental Principles of document.referrer
document.referrer is a read-only property defined in the DOM Level 2 specification that returns the URL of the page that directed the user to the current page. This property is particularly useful when users navigate to the current page by clicking links.
Basic Usage Examples
Here is a simple example demonstrating how to use document.referrer to obtain the previous page's URL:
const previousUrl = document.referrer;
if (previousUrl) {
console.log(`User came from: ${previousUrl}`);
// In practical applications, this information can be used for page transitions or state management
} else {
console.log('Unable to retrieve previous page information');
}Practical Application Scenarios
Consider an e-commerce website scenario where users click on products from a list page to view details, and we want to display a return link on the detail page:
// Get the previous page URL
const referrer = document.referrer;
// Create a back button
const backButton = document.createElement('button');
backButton.textContent = 'Back to Product List';
// If the previous page was the product list, add return functionality
if (referrer && referrer.includes('/products')) {
backButton.addEventListener('click', function() {
window.location.href = referrer;
});
} else {
// If not from product list, use default back functionality
backButton.addEventListener('click', function() {
history.back();
});
}
document.body.appendChild(backButton);Limitations of document.referrer
Although document.referrer is useful in many scenarios, it has important limitations:
When users directly type URLs into the address bar or use bookmarks to access pages, document.referrer returns an empty string because there is no explicit referral source.
If links use the rel="noreferrer" attribute, referral information will not be passed:
<a href="target.html" rel="noreferrer">No-referrer link</a>In some form submission scenarios, referral information may not be passed as expected, depending on browser-specific implementations.
Security and Privacy Considerations
Browsers impose strict limitations on accessing page history for security and privacy protection. If complete browsing history access were permitted, malicious websites could obtain users' browsing habits and visited site information.
The window.history object allows navigation operations but does not provide direct access to specific URLs in the session. This design balances functional requirements with user privacy protection.
Alternative Approaches and Supplementary Methods
Using history.back() for Navigation
If the goal is simply to return users to the previous page without needing the specific URL, the history.back() method can be used:
const backButton = document.getElementById('back-button');
backButton.addEventListener('click', function() {
history.back();
});Session Management Techniques
For scenarios requiring tracking of user navigation paths within the same website, consider these alternative approaches:
Using URL parameters to pass state information:
// Add source information when navigating from current page
function navigateWithReferrer(targetUrl) {
const currentUrl = window.location.href;
const separator = targetUrl.includes('?') ? '&' : '?';
window.location.href = `${targetUrl}${separator}from=${encodeURIComponent(currentUrl)}`;
}Utilizing localStorage or sessionStorage to store navigation history:
// Record current page on page load
const navigationHistory = JSON.parse(sessionStorage.getItem('navHistory') || '[]');
navigationHistory.push({
url: window.location.href,
timestamp: Date.now()
});
// Keep only the last 5 page records
if (navigationHistory.length > 5) {
navigationHistory.shift();
}
sessionStorage.setItem('navHistory', JSON.stringify(navigationHistory));Best Practice Recommendations
Always check if document.referrer has a value before using it to avoid unnecessary operations on empty values.
For critical business logic, do not rely entirely on document.referrer; have backup solutions prepared.
In single-page applications (SPAs), consider using navigation history features provided by routing libraries.
If cross-domain referral information is needed, ensure understanding of relevant CORS policy limitations.
Conclusion
The document.referrer property provides a simple and effective solution for obtaining previous page URLs, but developers must understand its applicable scenarios and limitations. In practical projects, selecting appropriate approaches based on specific requirements and combining them with other session management techniques can help build more robust and user-friendly web applications.