Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/418.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 关闭页面时发出警报,在页面赢得时执行操作';t关闭_Javascript - Fatal编程技术网

Javascript 关闭页面时发出警报,在页面赢得时执行操作';t关闭

Javascript 关闭页面时发出警报,在页面赢得时执行操作';t关闭,javascript,Javascript,在internet上找到一个工作脚本,但我无法更改FF的消息。那太好了。(适用于Chrome) 不管怎样,这很有效。但是我想在用户点击abort继续访问页面时做点什么 我该怎么做呢?如果用户决定留在页面上,您可以使用定时功能来做一些事情。在用户单击“确定”或“取消”之前,onbeforeunload显示的confirmbox将阻止执行。如果单击“取消”,将执行定时功能,否则页面将关闭,并且将永远不会执行定时功能 代码如下所示: window.addEventListener('beforeunl

在internet上找到一个工作脚本,但我无法更改FF的消息。那太好了。(适用于Chrome)

不管怎样,这很有效。但是我想在用户点击abort继续访问页面时做点什么


我该怎么做呢?

如果用户决定留在页面上,您可以使用定时功能来做一些事情。在用户单击“确定”或“取消”之前,
onbeforeunload
显示的confirmbox将阻止执行。如果单击“取消”,将执行定时功能,否则页面将关闭,并且将永远不会执行定时功能

代码如下所示:

window.addEventListener('beforeunload', function (e) {
    e.preventDefault();
    e.returnValue = 'Do you want to leave the page?';
    setTimeout(function () { // Timeout to wait for user response
        setTimeout(function () { // Timeout to wait onunload, if not fired then this will be executed
            console.log('User stayed on the page.');
    }, 50)}, 50);
    return 'Do you want to leave the page?';
});


您无法在FF中的confirmbox中显示消息,原因在RGraham在其评论中链接的帖子中的接受答案中解释。

可能与CVers重复,这不是重复,这里的问题是如何检测已发生的事件canceled@Kaiido上面的投票结束是一个很好的例子,为什么你应该每个问题问一个问题。@Nit,只有一个问题,好吧,关于FF,有一些关于不起作用的噪音,被标记为欺骗的东西,但这对我来说仍然不是问题。但是我同意这是没有必要的,而且提供的链接实际上是有用的,只是不是一个好的链接dupe@Kaiido这完全是一个解释的问题。你在JSFIDLE上的演示不适用于Chrome和FF。不是吗?如果我停留在页面上,它会在FF和Chrome的控制台中显示一条消息。确保您没有更改小提琴中的任何内容,在这种情况下,JSFIDLE自己的
onbeforeunload
处理程序可能会覆盖用户的事件。很好,谢谢!一个解决方案似乎在第一个解决方案中嵌套了另一个超时函数one@Kaiido看来你是对的。实际上IE不允许执行超时,但Chrome和FF会。我将在答案中添加第二个超时,以解决“所有”浏览器中的问题。
window.addEventListener('beforeunload', function (e) {
    e.preventDefault();
    e.returnValue = 'Do you want to leave the page?';
    setTimeout(function () { // Timeout to wait for user response
        setTimeout(function () { // Timeout to wait onunload, if not fired then this will be executed
            console.log('User stayed on the page.');
    }, 50)}, 50);
    return 'Do you want to leave the page?';
});