Check if page gets reloaded or refreshed in JavaScript

前端 未结 12 2857
遇见更好的自我
遇见更好的自我 2020-11-21 22:57

I want to check when someone tries to refresh a page.

For example, when I open a page nothing happens but when I refresh the page it should display an alert.

12条回答
  •  甜味超标
    2020-11-21 23:32

    I have wrote this function to check both methods using old window.performance.navigation and new performance.getEntriesByType("navigation") in same time:

    function navigationType(){
    
        var result;
        var p;
    
        if (window.performance.navigation) {
            result=window.performance.navigation;
            if (result==255){result=4} // 4 is my invention!
        }
    
        if (window.performance.getEntriesByType("navigation")){
           p=window.performance.getEntriesByType("navigation")[0].type;
    
           if (p=='navigate'){result=0}
           if (p=='reload'){result=1}
           if (p=='back_forward'){result=2}
           if (p=='prerender'){result=3} //3 is my invention!
        }
        return result;
    }
    

    Result description:

    0: clicking a link, Entering the URL in the browser's address bar, form submission, Clicking bookmark, initializing through a script operation.

    1: Clicking the Reload button or using Location.reload()

    2: Working with browswer history (Bakc and Forward).

    3: prerendering activity like

    4: any other method.

提交回复
热议问题