【发布时间】:2020-04-22 14:23:45
【问题描述】:
我想在用户点击浏览器“后退按钮”时警告他们,然后在确认后重定向他们。 下面是我的 JS 代码,但只适用于 firefox,我想让它也适用于 chrome 和其他浏览器。
注意:为了在 chrome 中触发事件,我需要先点击页面正文,然后点击浏览器的“返回”按钮(这不好)。
请帮忙。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page2</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script>
$(function(){
window.history.pushState({page: 1}, "", "");
window.onpopstate = function(event) {
if(event){
var confirm = window.confirm("Please, note that you may lose your move details by returning to the previous page.");
}
}
});
</script>
</body>
</html>
【问题讨论】:
-
在没有先前交互的情况下试图弄乱默认浏览器控件被认为是糟糕的用户体验。除了 Rahul 的回复,我认为最好阅读 this post 和 MDN page for beforeunload 描述该行为:“为了对抗不需要的弹出窗口,浏览器可能不会显示在 beforeunload 事件处理程序中创建的提示,除非页面已被交互有,甚至可能根本不显示它们。”
-
如果您想警告用户他们将丢失所做的更改,他们是否必须首先进行更改? (除非您以编程方式进行更改)
-
也许this 会有所帮助?在网页中自动执行点击事件。
标签: javascript jquery google-chrome safari cross-browser