Scenario
In JavaScript, we can get the URL of the previous page by using the document.referrer property. This property returns the URL of the previous page that the user came from.
If the document.referrer property doesn’t work for our specific use case or is not available, there are some alternative ways to get the previous page URL in JavaScript. Here are a few options:
Solution
- Using the History API:
// Get the previous page URL using the History API
var previousPageUrl = window.history.previous;
// Display the previous page URL in the console
console.log(“Previous page URL: ” + previousPageUrl);
2. Using cookies:
// Set a cookie with the current page URL
document.cookie = “currentUrl=” + window.location.href;
// Get the previous page URL from the cookie
var previousPageUrl = document.cookie.replace(/(?:(?:^|.*;\s*)currentUrl\s*\=\s*([^;]*).*$)|^.*$/, “$1”);
// Display the previous page URL in the console
console.log(“Previous page URL: ” + previousPageUrl);
3. Using Session Storage
// Set the current page URL in session storage
sessionStorage.setItem(“currentUrl”, window.location.href);
// Get the previous page URL from session storage
var previousPageUrl = sessionStorage.getItem(“previousUrl”);
// Display the previous page URL in the console
console.log(“Previous page URL: ” + previousPageUrl);
Note:- If we want to redirect to previous page without knowing Previous page URL then we can use below code.
<button onclick=”goBack()”>Continue Shopping</button>
<script>
function goBack() {
window.history.back();
}
</script>