'Is it possible to store previous url in back button which will work directly?
I am trying to store the previous url data in a back button so that the page can be shared directly without losing that information. I tried with javascript using the document referrer and with cookies but it doesn't work if the page is accessed directly. Thanks in advance.
Solution 1:[1]
Try something like this.
When a user visits the webpage, run this:
// When the user closes the window, save the url in a localStoage
window.onbeforeunload = () => {
localStorage.setItem('previousUrl', document.URL);
};
Once they revisit again, run this function:
// When the user open the webpage, it will show the data saved last time
function getPreviousUrl() {
return document.referrer ? document.referrer : localStorage.getItem('previousUrl');
}
// Return the url saved last time
getPreviousUrl();
Solution 2:[2]
you can use jquery insted of store data in cookies.
jQuery(document).ready(function($) {
if (window.history && window.history.pushState) {
window.history.pushState('forward', null, './#forward');
$(window).on('popstate', function() {
alert('Back button clicked...');
});
}
});
Solution 3:[3]
window.history.pushState(data, title, targetUrl);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | K.K Desgins |
| Solution 2 | Sachin Shah |
| Solution 3 | Richard Padre |
