Reputation: 19684
I am curious if there is a way to detect the browser refresh event in javascript specifically. We are using the jQuery.address plugin to provide forward and back button functionality to AJAX functions. The problem I am facing is that this plugin does not seem to detect if the user has refreshed the page.
This code is executed each time the user moves forward or back in the browser history. I would also like it to exexute when the user refreshes.
$.address.init(function(event) {
}).change(function(event) {
SummaryDiv.SwapPanels(newPanelID);
}
Any ideas?
Upvotes: 15
Views: 59058
Reputation: 11
In javascript you can do this:
page1.html
<script>
localStorage.removeItem('setear1')
</script>
page2.html
<script>
addEventListener('DOMContentLoaded', () => {
let vengoDeLaPaginaAnterior = localStorage.getItem('setear1')
if (vengoDeLaPaginaAnterior === null) {
localStorage.setItem('setear1', 1)
} else {
document.location.href = 'page1.html'
}
})
</script>
then: if user refresh page, return to previus page.
Upvotes: 1
Reputation: 18932
Along these lines, I had a page whose behavior I didn't want to repeat if refreshed, so I changed the hash programmatically as described in this answer.
checkRefresh: function() {
if (document.location.hash === '#visited') {
console.log('Refreshed');
return true;
} else {
document.location.hash = 'visited';
return false;
}
}
UPDATE
I found that at least Mobile Safari would ignore the hash if the refresh occurred automatically (e.g. page data expunged from cache before being viewed again). I ended up using a more complex solution described here.
Upvotes: 9
Reputation: 19684
I was able to force the change event code to run on refresh by
window.onload = $.address.update(function(){
...
})
Upvotes: 1
Reputation: 1260
Found this on the web for you...
Has both a javascript clever method along with a cookies method.
http://www.tedpavlic.com/post_detect_refresh_with_javascript.php
Upvotes: 4
Reputation: 5722
A naive attempt of mine would be to simply store the current state into some cookie after each change and simply load them again on each page load.
Upvotes: 5
Reputation: 15290
On a page refresh, the javascript is also reloaded. So couldn't you specify what you want to happen directly in jQuery's ready method?
Upvotes: 1