Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Browser Refresh in Javascript

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?

like image 946
Nick Avatar asked Jul 14 '10 15:07

Nick


People also ask

How do you know when a web page is refreshed?

A better way to know that the page is actually reloaded is to use the navigator object that is supported by most modern browsers. It uses the Navigation Timing API. thanks buddy this is accurate solution to detect either the page is reloaded from right click/refresh from the browser or reloaded by the url.

How do I know if my browser is refreshing or closing?

When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event. Now when ONUNLOAD event is triggered, there is no way to distinguish between refresh the page or close the browser.


5 Answers

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.

like image 178
Ben Flynn Avatar answered Oct 02 '22 06:10

Ben Flynn


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.

like image 39
LukeN Avatar answered Sep 29 '22 06:09

LukeN


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

like image 44
Capt Otis Avatar answered Sep 30 '22 06:09

Capt Otis


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?

like image 34
kingjeffrey Avatar answered Sep 30 '22 06:09

kingjeffrey


I was able to force the change event code to run on refresh by

  window.onload = $.address.update(function(){    
...
})
like image 28
Nick Avatar answered Oct 02 '22 06:10

Nick