关闭或刷新页面上的确认根本不起作用

Confirmation on close or refresh page not working at all

当用户关闭选项卡或刷新页面时,网站必须显示一个弹出窗口来确认这一点。 我试过这段代码:

window.onbeforeunload = function (e) {
    return confirm("Are you sure you want to leave this page?");
};

这在 firefox 或 chrome 中均无效。 在 Firefox 中没有弹出窗口出现。在 chrome 中,默认值也没有被覆盖。 我什至尝试使用以下代码但无济于事:

window.onbeforeunload = function (e) {
    var dialogText = 'Are you sure about this?';
    e.returnValue = dialogText;
    return dialogText;
};

如何解决这个问题? 任何代码片段都会有所帮助。谢谢。

来自 Firefox 的文档:

To combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with.

如果用户之前没有与页面交互,则无法显示弹出窗口。

我在互联网上找到了这个片段:

window.onbeforeunload = function (e) {
        return "Please click 'Stay on this Page' if you did this unintentionally";
    };

这完全符合要求。 我发现您实际上不需要添加任何确认电话。如果你只是 return 一个字符串,这将提示浏览器确认离开页面。大多数商业浏览器默认支持此功能。

从 Firefox 4、Chrome51、Opera 38 和 Safari 9.1 开始,将显示不受网页控制的通用字符串,而不是返回的字符串。例如,Firefox 显示字符串 "This page is asking you to confirm that you want to leave - data you have entered may not be saved."

-- 来自 Mozilla Developer Docs