【问题标题】:Clear Onbeforeunload卸载前清除
【发布时间】:2012-12-30 19:21:36
【问题描述】:

我有一个使用 ajax 提交的 textarea,它使用 onbeforeunload 警告用户如果他们尝试关闭浏览器,他们还没有提交 textarea。问题是我需要在ajax 提交成功的情况下以某种方式清除 onbeforeunload,以便 onbeforeunload 知道用户已成功提交表单。有没有办法用一行代码清除 onbeforeunload,类似于 clearTimeout 或 clearInterval?我将展示我目前拥有的 onbeforeunload 代码,尽管我认为这并不重要,因为我正在寻找一个不同的函数来清除它。请不要框架。谢谢。

函数调用

unsavedChangesWarning();

Onbeforeunload 函数

function unsavedChangesWarning(){
    window.onbeforeunload = function(){
        return 'If you close this page you will lose your stride update!';
    };
}

【问题讨论】:

    标签: javascript ajax


    【解决方案1】:

    window.onbeforeunload = null 将清除它。只需在尝试将用户重定向到任何地方之前添加它即可。

    【讨论】:

    • 根据developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/…,“当此事件返回(或将returnValue属性设置为)非null或未定义的值时,将提示用户确认页面卸载。”至少 FF 61 并非如此。我进行了测试以返回 null 并将 e.returnValue 设置为 null,对话框仍然显示。真正有效的是像 Niet the Dark Absol 或 danielson317 建议的那样挂断听众。
    【解决方案2】:

    对于 jQuery,这看起来像:

    $(window).on('beforeunload', function (e)
    {
      return 'Please dont leave me';
    });
    
    $(window).off('beforeunload');
    

    如果用户会话过期,我实际上将使用上述解决方案来允许干净刷新。但是,对于您的用例,我认为在卸载前简单地设置 on 更有意义。

    $('input, textarea, select').change(function()
    {
      $(this).parents('form').addClass('dirty');
    });
    window.onbeforeunload = function()
    {
      if ($('form.dirty').length)
      {
        var confirmationMessage = 'You have edited but not saved a form on this page.';
    
        (e || window.event).returnValue = confirmationMessage; //Gecko + IE
        return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-07-14
      • 1970-01-01
      • 2020-01-25
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      • 2022-06-17
      相关资源
      最近更新 更多