Reputation: 25
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.
Upvotes: 0
Views: 2027
Reputation: 5359
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();
Upvotes: 1
Reputation: 4533
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...');
});
}
});
Upvotes: 0