【问题标题】:Notify user on browser close only仅在浏览器关闭时通知用户
【发布时间】:2013-08-19 09:30:48
【问题描述】:

我正在尝试在用户关闭或重新加载页面时实现通知。目前我正在使用以下代码

function unloadPage(){
    return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;

这很好用。但问题是每当发生导航时都会发生这种情况。要么是页面刷新,要么是表单提交,要么是超链接点击,要么是发生任何导航。我只想为浏览器使用此代码刷新和关闭。我知道设置一个标志并检查它。 但是我必须把它集成到一个大的应用程序中。所以很难在每个页面中添加代码。所以有没有简单的方法。 有没有办法捕捉刷新或浏览器 cosing 以便可以使用它。

【问题讨论】:

  • 您无法捕获浏览器关闭请求。但是,当您知道要提交表单或单击链接时,您可以删除 onbeforeunload 处理程序。d

标签: javascript jquery events browser browser-close


【解决方案1】:

请注意,在您的代码中,您使用的是onbeforeclose,但事件名称是beforeunload,所以属性是onbeforeunload,而不是onbeforeclose

我只想将此代码用于浏览器刷新和关闭。有没有办法捕捉刷新或浏览器 cosing 以便可以使用它。

没有。相反,您必须捕获每个链接和表单提交,并设置一个标志告诉您的 onbeforeunload 处理程序不要返回字符串,或者删除您的 onbeforeunload 处理程序(可能该标志更干净)。

例如:

var warnBeforeClose = true;
function unloadPage(){
    if (warnBeforeClose) {
        return "Your changes will not be saved.";
    }
}
window.onbeforeunload = unloadPage;

// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
    // Don't warn
    warnBeforeClose = false;

    // ...but if we're still on the page a second later, set the flag again
    setTimeout(function() {
        warnBeforeClose = true;
    }, 1000);
}

或者没有setTimeout(但仍然有超时):

var warningSuppressionTime = 0;
function unloadPage(){
    if (+new Date() - warningSuppressionTime > 1000) { // More than a second
        return "Your changes will not be saved.";
    }
}
window.onbeforeunload = unloadPage;

// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
    // Don't warn for the next second
    warningSuppressionTime = +new Date();
}

2017 年更新:另请注意,至少在几年前,浏览器不会显示您返回的消息;他们只是使用您返回 null 以外的其他内容的事实作为标志来显示他们自己的内置消息。

【讨论】:

  • 但是我必须把它集成到一个大应用程序中。所以很难在每个页面中添加代码。所以有没有简单的方法。
  • @User016:这简单的方法。您已经在每一页上都有代码。大概该代码是集中的(在每个页面上包含的某些文件中)。如果没有,请将其集中起来,这样您就不会到处重复代码。然后只需将以上内容添加到集中式代码中即可。
  • 我遵循了您建议的第一种方法。但在某些情况下它会失败,我不知道为什么。一个是在按钮单击时发生重定向的情况。我不想通知那些时间所以我在代码中添加了$("button").on('click',dontWarn);。但有时如果失败并产生警报。你有什么建议
  • @User016:您的按钮真的是button 元素吗?不是input[type=button]
  • <button name="Cancel" id="Cancel" type="button">Cancel</button>.这是代码不起作用的按钮之一
【解决方案2】:

查看this link

它为您提供有关如何处理 onbeforeunload 事件的信息。

这个想法是在页面上有一个全局标志。当对字段进行任何更改时,此标志设置为 true。单击保存按钮时,需要将此标志设置为 false。

onbeforeunload 事件中,检查标志是否为真,然后显示相应的消息。

var needToConfirm = true;

window.onbeforeunload = confirmExit;
function confirmExit()
{
    if (needToConfirm)
    {
        // check on the elements whether any change has been done on the fields.
        // If any change has been done, then set message here.
    }
}

function saveClicked()
{
    needToConfirm = false;
}

【讨论】:

    【解决方案3】:

    解决您的问题的一个简单方法是设置一个标志,然后仅在该标志有效时调用您的函数。在这种情况下,您可以将锚标记、F5 键和表单提交按钮单击绑定到将标志设置为 false 的事件。因此,只有在上述情况没有发生时,您的警报栏才会可见:)

    这是脚本:

    var validNavigation = false;
    
    function endSession() {
      // Browser or broswer tab is closed
      alert("bye");
    }
    
    function wireUpEvents() {
    
      window.onbeforeunload = function() {
          if (!validNavigation) {
             endSession();
          }
      }
    
      // Attach the event keypress to exclude the F5 refresh
      $(document).bind('keypress', function(e) {
        if (e.keyCode == 116){
          validNavigation = true;
        }
      });
    
      // Attach the event click for all links in the page
      $("a").bind("click", function() {
        validNavigation = true;
      });
    
      // Attach the event submit for all forms in the page
      $("form").bind("submit", function() {
        validNavigation = true;
      });
    
      // Attach the event click for all inputs in the page
      $("input[type=submit]").bind("click", function() {
        validNavigation = true;
      });
    
    }
    
    // Wire up the events as soon as the DOM tree is ready
    $(document).ready(function() {
      wireUpEvents();  
    });
    

    【讨论】:

    • 这不适用于所有浏览器,如果元素已经自己处理指定的事件。
    【解决方案4】:

    DEMO

    (运行或刷新小提琴以查看警报onbeforeunload() 事件消息并单击链接“kk”,它不会显示onbeforeunload() 事件消息。在您的网页中尝试)

    我有一个解决方案,你不必为每个标签添加 onclick 事件。

    只需将其添加到页面上的任何位置即可。

    <input type="hidden" value="true" id="chk"/>
    

    并将此代码添加到您的文档头标签

    <script>
    window.onbeforeunload = confirmExit;
    function confirmExit()
    {
       if(document.getElementById("chk").value=="true")
       {
          return "Your changes will not be saved.";
       }
    }
    
    document.onclick = myClickHandler;
    function myClickHandler() {
          document.getElementById("chk").value="false";
        }
    <script>
    

    希望对你有帮助

    谢谢

    【讨论】:

    • 这仅在您的元素上没有 onclick 事件处理程序时才有效。一旦您这样做,chk 值将设置为 false,并且不会显示确认。
    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2016-07-10
    相关资源
    最近更新 更多