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

前端 未结 4 1015
说谎
说谎 2020-12-06 00:43

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 t

相关标签:
4条回答
  • 2020-12-06 01:23

    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.

    0 讨论(0)
  • 2020-12-06 01:23
    $(function () {
        if (performance.navigation.type == 1) {
            yourFunction();
        }
    });
    

    More about PerformanceNavigation object returned by performance.navigation

    0 讨论(0)
  • 2020-12-06 01:38

    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
        }
    }​
    
    0 讨论(0)
  • 2020-12-06 01:46

    If it is refreshing, 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?";
    }
    
    0 讨论(0)
提交回复
热议问题