javascript - 使用当前浏览器离开页面之前的自定义消息

标签 javascript jquery cross-browser alert

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

我已经看到更改警报消息的可能性 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 警报? 谢谢

最佳答案

您可以尝试的另一个实现:

<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>

关于javascript - 使用当前浏览器离开页面之前的自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45936710/

相关文章:

javascript - 为什么 map 上的圆圈大小会变化?

javascript - Spring MVC Controller 不拦截 Ajax POST

java - 如何使用jsp和servlet将多个图像上传到文件夹中

径向渐变的CSS浏览器检测?

Angular 6 : what is the Reflect API in polyfills. TS?

javascript - 为什么这个 anchor 说 "search is not a function"?

javascript - 如何在 Python 和 JavaScript 中对 "json"嵌套字典进行相同的哈希处理?

javascript - 我怎样才能对 jQuery AJAX 查询进行分组?

jquery - '$' 未定义。如何在空的 ASP.NET MVC 4 项目中使用 jQuery 2.0.1?

html - "Box Model"CSS有多少种类型?