I would like to warn the user when they click on the browser "back button" then redirect them upon confirmation. Below is my JS code but works only in firefox, I would like to make it work in chrome and other browsers as well.
Note: In order for the event to be fired in chrome, I need first to click on the page body then click on browser "back" button(this is not good).
Please assist.
<!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>
I'd found a useful link, which explains such a behavior of Chrome and other browsers.
"Chrome plans to save you from sites that mess with your back button"
Some of the nuisance sites mentioned in above post, uses this behavior, in their favor. So, it seems that browsers like Chrome are intentionally preventing these kind of sneaky hacks with the "back button" (obviously due to security reasons and smooth user-experience). Also, I doubt if anyone finds a pretty hack, then Chrome developers will again evolve their security checks, as said in the post.
Anyways, we still have Firefox with us. Good luck ;)
Just like you said you first need to click on the body to activate confirm dialog and whenever user tries to leave the page will show the confirmation dialog.
window.onbeforeunload = (event) => {
event.preventDefault();
event.returnValue = '';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With