gpt4 book ai didi

javascript - onbeforeunload 在 Windows Chrome 中不起作用

转载 作者:行者123 更新时间:2023-11-30 16:06:33 25 4
gpt4 key购买 nike

我之前看到过这个问题,但 onbeforeunload 在 Windows Chrome 中对我不起作用。我使用的是版本 49.0.2623.112 m。这是我的代码:

<body onbeforeunload="handleBrowserCloseButton();">

function handleBrowserCloseButton() {

//Call method by Ajax call
alert('Browser close button clicked');

}

当我离开页面或关闭浏览器窗口时,没有任何反应。任何帮助将不胜感激。

最佳答案

您需要从回调函数返回一个非空值,否则您将看不到消息对话框。

所以你需要改变两件事:

<body onbeforeunload="return handleBrowserCloseButton();">

function handleBrowserCloseButton() { 
return 'Browser close button clicked';
}

除此之外你应该使用 window.addEventListener('beforeunload', ... )相反。

MDN: WindowEventHandlers.onbeforeunload: Notes :

When this event returns a non-void value, the user is prompted to confirm the page unload. In most browsers, the return value of the event is displayed in this dialog. In Firefox 4 and later the returned string is not displayed to the user. Instead, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved." See bug 588292.

因为该功能不应该被误用以防止用户表单离开页面,所以像alert这样的功能或 confirmonbeforeunload 中不起作用回调。

MDN: WindowEventHandlers.onbeforeunload: Notes :

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details.

关于javascript - onbeforeunload 在 Windows Chrome 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36958723/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com