window.onbeforeunload runs only when closing window not on refresh

耗尽温柔 提交于 2019-12-03 14:14:43

问题


I have this function

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

and I have a button that when the user presses it the window refreshes to update screen values and do some database calls. I added window.onbeforeunload=null; in the beginning of the function to disable onbeforeunload but it kept being called.

Is there a way to either disable the onbeforeunload function in my button onclick function or make the window.onbeforeunload get called only on close window not on refresh?


回答1:


Following code should work (should be kept inside head tag between script tags)

window.onload=function(){

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

    document.getElementById('refresh').onclick=function(){
        window.onbeforeunload = null;
        window.location.reload(); // replace with your code
    }
}​

WORKING DEMO.




回答2:


Another approach is to use Cookies. set the cookie as a flag as when you want to refresh the page without having the onbeforeunload function call.

 window.onbeforeunload = function (e) { 
...      
   canceled = getCookie("canceled");
         if (canceled == "false" || canceled == undefined)
          {//do ur stuff here
          }
...
}

and set your cookie to 5 secs so it expires right after you reload the page.



来源:https://stackoverflow.com/questions/11085998/window-onbeforeunload-runs-only-when-closing-window-not-on-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!