window.onbeforeunload在页面刷新而不是页面关闭时执行

Jav*_*yer 10 javascript onbeforeunload

window.onbeforeunload当发生关闭事件时,我正在使用弹出确认对话框,但页面刷新时会出现确认对话框,并且不会在页面关闭时执行.

这是JavaScript代码:

<script language="JavaScript">
    window.onbeforeunload = confirmWinClose();
    function confirmWinClose() {
        var confirmClose = confirm('Close?');
        return confirmClose;
    }    
</script>
Run Code Online (Sandbox Code Playgroud)

我在Chrome,Firefox和Internet Explorer上尝试过它.

gau*_*430 6

与您的代码有关的问题:

你这个函数会被调用refresh,因为on refresh the page is unloaded and then reloaded.

在你的解决方案中,你还应该注意到你没有分配一个function,window.onbeforeunload但你在分配return value of the function时写的是

window.onbeforeunload = confirmWinClose();
Run Code Online (Sandbox Code Playgroud)

每当完成任务时,它也可以执行该功能(基于你将它放在javascript中的位置).例如

function confirmWinClose() {
var confirmClose = confirm('Close?');
return confirmClose;
}

window.onbeforeunload = confirmWinClose();
Run Code Online (Sandbox Code Playgroud)

confirmWinClose只要加载了这个js ,上面的代码就会执行该函数.

(不是你的情况,因为你已经在调用后定义了函数,因此在加载时不会执行,但你应该记住这一点)

解:

以下解决方案close也在努力

而不是你的解决方案,我试过这个

JS:

window.onbeforeunload = function() {
    var confirmClose = confirm('Close?');
    return confirmClose;
}
Run Code Online (Sandbox Code Playgroud)

要么

 window.onbeforeunload = confirmWinClose; //note the absence of calling parantheses

    function confirmWinClose() {
        var confirmClose = confirm('Close?');
        return confirmClose;
    }
Run Code Online (Sandbox Code Playgroud)

这按预期工作.

还要注意的是,你应该returnonbeforeunload明确.

即使你必须调用一个函数,你也应该这样做

<script>
    window.onbeforeunload = function(e) {
       callSomeFunction();
       return null;
    };
</script>
Run Code Online (Sandbox Code Playgroud)


Pau*_*Rad 3

没有完整的解决方案,但您可以拦截F5键(如果用户单击刷新浏览器按钮则不会拦截...)

var isRefresh = false;

// with jquery

$(function() {
  $(document).on("keydown", function(e) {
    if (e.which === 116)
    {
      isRefresh = true;
    }
  });
});

window.onbeforeunload = function() {
 if (! isRefresh)
 {
   return confirm ('Close ?');
 }
 return false;
};
Run Code Online (Sandbox Code Playgroud)