首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Back-Button:询问用户是否想退出

Back-Button:询问用户是否想退出
EN

Stack Overflow用户
提问于 2022-01-13 11:34:30
回答 1查看 43关注 0票数 -1

我有一个有按钮的应用程序。如果用户单击按钮,就会出现一个带有文本的图层。

还有一个

history.pushState()

以捕捉“后退按钮”事件。

如果用户在浏览器中单击"back“,应该询问她是否真的想离开。如果她确认了,该层应该消失,history.state应该被设置为back() (或移除)。

否则,浏览器历史记录就不会有任何变化!

我试过使用befureonload事件侦听器,但是它没有任何效果.(这并不奇怪,因为状态更改可能不是卸载事件)。

这是我的钢笔:https://codepen.io/kili123/pen/QWqzjvN

我将感谢任何帮助和建议!

代码语言:javascript
复制
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")
  
  
})
代码语言:javascript
复制
#layer {
  background:#ddd;
  padding:2em;
}

.hidden {
  display:none;
}
代码语言:javascript
复制
<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>

EN

回答 1

Stack Overflow用户

发布于 2022-01-13 11:51:04

您可以尝试popstate事件处理程序,例如:

代码语言:javascript
复制
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);

注意:为了获得最好的结果,您应该只在您希望实现逻辑以避免任何其他意外问题的特定页面上加载此代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70695911

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档