9

我需要一个消息脚本,它只会在人们离开当前网页而不是当前网站时出现。

当人们完全离开网站时,会出现消息,他们需要按 OK 按钮以停留在当前页面(并取消离开网站)。

当人们实际停留在网站上或单击内部链接或页面时,该脚本可能不会运行。

这可以做到吗?

4

3 回答 3

6

查看这个非常基本的示例解决方案。它设置onbeforeunload处理程序,但如果用户单击内部链接,则将其删除。下面是示例解决方案中代码的通用版本。

HTML

<a href="internal_link.html">internal link</a>
<a href="http://www.example.com">external link</a>

JS(使用jQuery):

window.onbeforeunload = function(){
    return "Are you sure you want to leave our website?";
}
$(function(){
    $('a, input, button').click(function(){
            window.onbeforeunload = null;
    });
});
于 2010-05-28T00:04:56.153 回答
1

In most cases you don't need a popup for all events except the one: user closes the window.

Here is my solution for this:

$(window).on('beforeunload', function() {
    /* whatever you want here */
}   

$(document).on('click keydown', function(){
    $(window).off('beforeunload');
});
于 2012-09-24T22:54:49.470 回答
1

我遇到了类似的问题。但是在我的情况下,如果有人按 F5 或关闭窗口,则该消息应该根据用户的语言进行翻译。

按照我的小例子。

<html>
<head>
<script type="text/javascript">
function closeThis()
{
    if (window.confirm("Minha mensagem!")){
        window.close();
    }
}

function test() 
{
    // Add a warning in case anyone tries to navigate away or refresh the page
    return confirm("Minha mensagem");
}


</script>
</head>
<body onbeforeunload=test();>
<p>Hello World! Press F5 or Close this Window</p>
</body>
</html>
于 2012-02-16T18:15:35.870 回答