gpt4 book ai didi

javascript - 如何捕获 Firefox 中未保存更改的 "Stay on Page"按钮?

转载 作者:行者123 更新时间:2023-12-03 01:40:39 26 4
gpt4 key购买 nike

我正在开发一个应用程序,我需要能够检测用户何时收到模式对话框:

This page is asking you to confirm that you want to leave - data you have entered may not be saved

我还希望它按下“留在页面上”按钮。这可以用 JavaScript 实现吗?

我查看了其他似乎谈论退出页面的线程,但实际上我想在他们按下“留在页面上”按钮后立即执行一些处理。

我们是否有权访问此对话框上的这些按钮 - 如果可以,如何访问?

最佳答案

如果您想拦截尝试离开页面的用户(通过关闭浏览器选项卡或导航离开),您可以使用 window.onbeforeunload。根据浏览器的不同,从该函数返回的字符串可能会显示在导航确认对话框上。

window.onbeforeunload = function(){
return 'Your data will be lost if you leave now. Are you sure?';
};

不幸的是,无法从此对话框中获得确认,因为它是由浏览器控制的。

但是,您可以在该函数中为自己设置一个标志,然后在用户不离开页面时使用react:

window.onbeforeunload = function(){
userWantsToLeave = true;
return 'Your data will be lost if you leave now. Are you sure?';
};

window.onfocus = function() {
if(userWantsToLeave) {
// user attempted leaving but changed its mind, do actions here
userWantsToLeave = false;
}
}

看到这个 fiddle :http://jsfiddle.net/ec8mtj51/

编辑:MDN documentation 上所述对于 WindowEventHandlers.onbeforeunload,从 onbeforeunload 返回的字符串不再呈现给用户:

Starting with Firefox 44, Chrome 51, Opera 38 and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example, Firefox displays the string "This page is asking you to confirm that you want to leave - data you have entered may not be saved."

关于javascript - 如何捕获 Firefox 中未保存更改的 "Stay on Page"按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50856776/

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