user957178
user957178

Reputation: 631

How to check page is reloading or refreshing using jquery or javascript?

I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.

is there any event which can tell you page is doing filer? refresh or paging? using javascript?

Thanks

Upvotes: 18

Views: 44360

Answers (4)

SeanCannon
SeanCannon

Reputation: 77956

If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.

// From MDN
window.onunload = unloadPage;
function unloadPage()
{
    alert("unload event detected!");
}

https://developer.mozilla.org/en/DOM/window.onunload

If you just want a confirmation box to allow them to stay, use this:

window.onbeforeunload = function() {
    return "Are you sure you want to navigate away?";
}

Upvotes: 21

Aurora
Aurora

Reputation: 725

$(function () {
    if (performance.navigation.type == 1) {
        yourFunction();
    }
});

More about PerformanceNavigation object returned by performance.navigation

Upvotes: 1

Jason Morello
Jason Morello

Reputation: 11

There are some clarification notes on wrestling with this I think are critical.

First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.

From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.

I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:

  1. close the current window (fires onbeforeunload and onunload js events).
  2. request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.

These happen in just that order as well. Only a custom or non standard browser will behave differently.

Upvotes: 1

palaѕн
palaѕн

Reputation: 73886

You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:

HTML

<body onLoad="CheckPageLoad();">

    <input type="hidden" name="visit" id="visit" value="" />

</body>

JS

function CheckPageLoad() {
    if (document.getElementById("visit").value == "") {
        // This is a fresh page load
        document.getElementById("visit").value = "1";
    }
    else {
        // This is a page refresh
    }
}​

Upvotes: 3

Related Questions