【问题标题】:How to show message to user when new tab is opened打开新标签时如何向用户显示消息
【发布时间】:2014-03-04 23:35:40
【问题描述】:

下面的代码使用onbeforeunload 在用户离开网站之前显示一条消息。

$(window).on('beforeunload', function(){
    //  Was the <a> tag clicked?
    if(isClicked)
    {
        //  Reset isClicked
        isClicked = false;
        //  Display the message
        return 'You are leaving the site.';
    }
});

//  Define a clicked state variable with a default value;
isClicked = false;

$(window).load(function(){
    //  Get all tags with the specified className
    var anchors = $('.leaveSite');

    //  Add the "onclick" listener to each one of them
    anchors.each(function(index) {
        $(this).click(function(){
            isClicked = true;
        });
    });
});

我认为 onbeforeunload 在打开新窗口/标签时起作用。 当用户点击打开一个新窗口/标签&lt;a class="leaveSite"&gt; 时,我该如何做到这一点?

【问题讨论】:

    标签: jquery html browser dom-events


    【解决方案1】:

    要显示消息,是否应该这样写onbeforeunload函数

    $(window).on('beforeunload', function(){
        //  Was the <a> tag clicked?
        if(isClicked)
        {
            //  Reset isClicked
            isClicked = false;
            //  Display the message
            alert 'You are leaving the site.';
        }
    });
    

    【讨论】:

    • 这取决于我想做什么。根据我的需要,在onbeforeunload 上返回一个字符串将导致浏览器弹出一条消息,其中包含我提供的字符串以及离开站点或留下并取消重定向的选项。这是我在 stackoverflow 上的其他帖子中学到的一个巧妙的功能。
    【解决方案2】:

    如果有其他答案比这个更好,我很乐意接受。

    经过一些测试,我得出结论,当链接打开一个新窗口/标签时,我无法触发 onbeforeunload 事件。这很简单,因为在这些情况下,永远不会告诉 window 对象卸载(因为新页面会加载到其他地方),因此onbeforeunload 永远不会触发。 p>

    如果将来有一个新事件在当前页面打开新的浏览器窗口或标签页时触发可能会很好。

    对于这种情况,最好在 HTML 标记中添加 onclick="myAlert();" 属性并让函数执行以下操作:

    function myAlert() {
        alert("A new window/tab is about to be opened.");
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-22
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多