我有一个有按钮的应用程序。如果用户单击按钮,就会出现一个带有文本的图层。
还有一个
history.pushState()
以捕捉“后退按钮”事件。
如果用户在浏览器中单击"back“,应该询问她是否真的想离开。如果她确认了,该层应该消失,history.state应该被设置为back() (或移除)。
否则,浏览器历史记录就不会有任何变化!
我试过使用befureonload事件侦听器,但是它没有任何效果.(这并不奇怪,因为状态更改可能不是卸载事件)。
这是我的钢笔:https://codepen.io/kili123/pen/QWqzjvN
我将感谢任何帮助和建议!
window.addEventListener("beforeunload",function() {
alert("Wirklich verlassen?")
})
let button = document.querySelector("#button")
button.addEventListener("click",function() {
history.pushState({action: 'show_calendar'}, "Layer");
let layer = document.querySelector("#layer")
layer.classList.remove("hidden")
})#layer {
background:#ddd;
padding:2em;
}
.hidden {
display:none;
}<button id="button">Click me</button>
<div id="layer" class="hidden">
Hello here i am. If you press "back" in your browser there should be a confirmation if you really want to close.</div>
发布于 2022-01-13 11:51:04
您可以尝试popstate事件处理程序,例如:
window.addEventListener('popstate', function(event) {
// The popstate event is fired each time when the current history entry changes.
var r = confirm("You pressed a Back button! Are you sure?!");
if (r == true) {
// Call Back button programmatically as per user confirmation.
history.back();
// Uncomment below line to redirect to the previous page instead.
// window.location = document.referrer // Note: IE11 is not supporting this.
} else {
// Stay on the current page.
history.pushState(null, null, window.location.pathname);
}
history.pushState(null, null, window.location.pathname);
}, false);注意:为了获得最好的结果,您应该只在您希望实现逻辑以避免任何其他意外问题的特定页面上加载此代码。
https://stackoverflow.com/questions/70695911
复制相似问题