I have an app with a button. If a user clicks on the button, a layer appears with some text.
Also there is a
history.pushState()
in order to catch the "Back button" event.
If the user clicks on "back" in her browser, she should been asked if she really wants to leave. And if she confirmes, the layer should disappear and the history.state should be set to back() (or removed).
Otherwise there should be no change to the browser history!
I tried using the befureonload event listener but it did not have any effect... (not too surprisingly as a state change is probably not an unload event).
This is my pen: https://codepen.io/kili123/pen/QWqzjvN
I would appreciate any help and suggestions!
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>
You can try popstate event handler, e.g:
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);
Note: For the best results, you should load this code only on specific pages where you want to implement the logic to avoid any other unexpected issues.