【问题标题】:Custom message before leaving a page with current browsers使用当前浏览器离开页面之前的自定义消息
【发布时间】:2017-08-29 18:31:01
【问题描述】:

在一个页面上,我有一个复杂的表单(许多字段、选项卡...),我想显示一条警告消息以警告用户如果他试图离开页面,无论他是否发布了表单(因为在编辑表单中,您设置了所有必填字段,但您可以修改或不修改这些值。

我已经看到更改警报消息has been remove as Chrome 51 的可能性,并且无论如何都不适用于其他浏览器,但我想在页面更改之前显示一条消息,但我想显示它在实际默认 Chrome/FF、IE ... 弹出警报之前

我或多或少在 this situation 中,但 Chrome 51 之后的答案不再相关。

所以,来自this question

我做到了

(function ($) {
  'use strict';

$(window).bind('beforeunload', function(e) {
  e.preventDefault();
  $('<div title="Attention !">Vous souhaitez quitter cette page. Avez-vous enregistré les données du formulaire ? Si non, choisissez "rester sur la page" lors de l\'affichage de l\'alerte.</div>').dialog({
    modal:true,
    close: function(){$(this).dialog('destroy').remove();},
    position: { my: "center top", at: "center", of: window }
  });
  return "Random message to trigger the browser's native alert.";
});

}(jQuery));

the fiddle

但这会在浏览器警报之后显示 jQueryUI 警报消息,所以它真的没有用。

截至 2017 年浏览器使用情况,我如何在实际浏览器警报之前显示此 jquery 警报? 谢谢

【问题讨论】:

    标签: javascript jquery cross-browser alert


    【解决方案1】:

    您可以尝试的另一种实现方式:

    <html>
      <head>
        <script type="text/javascript">
          var hook = true;
          window.onbeforeunload = function() {
            if (hook) {
              return "Did you save your stuff?"
            }
          }
          function unhook() {
            hook=false;
          }
        </script>
      </head>
      <body>
        <!-- this will ask for confirmation: -->
        <a href="http://google.com">external link</a>
    
        <!-- this will go without asking: -->
        <a href="anotherPage.html" onClick="unhook()">internal link, un-hooked</a>
      </body>
    </html>
    

    【讨论】:

    • 在 Chrome 版本 63(大约 2018 年)中,这是可行的。但是,您会收到 Chrome 默认消息“您所做的更改可能无法保存”,而不是收到警告“您保存了您的东西吗?”。我确信有一个解决方法,但对我来说,默认消息就足够了。
    猜你喜欢
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多