在一个页面上,我有一个复杂的表单(许多字段、选项卡...),我想显示一条警报消息,以警告用户如果他尝试离开该页面,无论他是否发布了该表单(因为在编辑表单中,您已设置所有必填字段,但您可以修改或不修改这些值)。
我已经看到更改警报消息的可能性 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));
但这会在浏览器警报之后显示 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/