prevent OnBeforeUnload() event from happening in refresh/F5

白昼怎懂夜的黑 提交于 2019-12-05 00:09:33

问题


I'm using onbeforeunload event to perform operations during the closing page.
I do not want the event to happen in the case of Refresh / F5.

Is there a way or other event to do this?


回答1:


Unfortunately onbeforeunload event listens the page state in the browser. Going to another page as well as refreshing will change the page state, meaning onbeforeunload will be triggered anyway.

So I think it is not possible to catch only refresh.

But, if you'll listen and prevent Keypress via JavaScript, then it can be achieved.

Refresh can be done via F5 and CtrlR keys, so your goal will be to prevent these actions.

using jQuery .keydown() you can detect these keycodes:

For CtrlR

$(document).keydown(function (e) {
    if (e.keyCode == 65 && e.ctrlKey) {
        e.preventDefault();
    }
});

For F5

$(document).keydown(function (e) {
    if (e.which || e.keyCode) == 116) {
        e.preventDefault();
    }
});



回答2:


I would use the keydown listener to check for F5 and set a flag var.

http://api.jquery.com/keydown/

Detecting refresh with browser button is not that easy/possible.




回答3:


I wanted to add a message alert onbeforeunload, so my solution was this one:

  $(document).ready(function(){
        window.onbeforeunload = PopIt;
        $("a").click(function(){ window.onbeforeunload = UnPopIt; });
        $(document).keydown(function(e){
            if ((e.keyCode == 82 && e.ctrlKey) || (e.keyCode == 116)) {
                window.onbeforeunload = UnPopIt;
            }
        });
  });

  function PopIt() { return "My message before leaving"; }
  function UnPopIt()  { /* nothing to return */ }

Third line ($("a").click...) is to avoid showing the alert when navigating between sections of the web.



来源:https://stackoverflow.com/questions/19536220/prevent-onbeforeunload-event-from-happening-in-refresh-f5

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