How to detect browser refresh alone

前端 未结 1 467
时光取名叫无心
时光取名叫无心 2021-01-26 13:48

Hi i want to detect browser refresh alone in javascript. The below code am using is detecting the browser close as well as refresh, back etc.

window.onbeforeunlo         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-26 14:07

    You can save the current time to session storage from onbeforeunload, then when the page loads look in session storage for a time and, if you find one and it's within (say) a couple of seconds, assume it's a refresh.

    window.onbeforeunload = function() {
        sessionStorage.setItem("left", Date.now());
    };
    

    and elsewhere, in code that runs when the page loads:

    var left = sessionStorage.getItem("left");
    if (left && (Date.now() - left) < 2000) {
        // Refreshed
    }
    

    Full example (live copy):

    (function() {
        "use strict";
    
        window.onbeforeunload = function() {
            sessionStorage.setItem("left", Date.now());
        };
    
        var left = sessionStorage.getItem("left");
        if (left && (Date.now() - left) < 2000) {
            // Refreshed
            display("Refreshed");
        } else {
            // Freshly loaded
        }
    })();
    

    0 讨论(0)
提交回复
热议问题