单击' x'按钮?

发布于 2025-01-28 07:42:58 字数 520 浏览 3 评论 0原文

当用户单击X按钮以关闭浏览器的窗口时,我想显示一个对话框。在对话框中,它将询问用户是否要继续关闭,如果用户选择no,则不会关闭窗口。

我想知道如何实现这一目标。我尝试了卸载事件处理程序,触发了代码,但窗口已经关闭。我还尝试了onBeForeunLoad,但似乎根本没有触发。

window.addEventListener('onbeforeunload ', () => {
   // code not triggered here
});

window.addEventListener('unload', () => {
   // code triggered but window is already closed
});

即使我们假设有一个事件处理程序将在窗口关闭之前触发,那么我应该编写什么代码以防止关闭窗口?看起来像x按钮单击了,窗口只是“确定”要关闭而不是可逆的吗?

I want to show a dialog when users click the X button to close the browser's window. In the dialog, it will ask users if they want to proceed with closing or not, if users choose no, it won't close the window.

I am wondering how to achieve this. I tried the unload event handler, the code was triggered but the window has already been closed. I also tried onbeforeunload, but it seems not triggered at all.

window.addEventListener('onbeforeunload ', () => {
   // code not triggered here
});

window.addEventListener('unload', () => {
   // code triggered but window is already closed
});

Even if we assume that there is an event handler which will be triggered before the window is closed, then what code should I write in order to prevent closing the window? It looks like once X button is clicked, the window is just "determined" to close and it's not reversible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

久隐师 2025-02-04 07:42:58

[https://stackoverflow.com/questions/2923139/prompt-user-before-browser-close]

这是做的基本方法
但是提示总是一样

window.onbeforeunload = function(evt) {
   return true;
}

[https://stackoverflow.com/questions/2923139/prompt-user-before-browser-close]

this is the basic way to do
but prompt will be always the same

window.onbeforeunload = function(evt) {
   return true;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文