My script
<script type="text/javascript">
var hook = true;
window.onbeforeunload = function() {
if (hook) {
return "Do you sure what to leave"
}
}
function unhook() {
hook=false;
}
</script>
This code blocks user when
I only want to block user when they try to close browser or tab.
This is normally used to prevent users lost their drafts from unexpected page leave actions, so normally we will only set this up when user typed something in a input/textarea etc..., and it's predictable user action (cause we can detect if user entered anything or not).
But, you want to block user only when they're trying to close browser or tab, this is not a predictable action, and it cannot always be detectable (such like closing browser).
So, if you want to do so, I think you need to attach listeners to any other acceptable page leave actions (like those you mentioned), and cancel blocking by returning null/false in onbeforeunload.
For example, this accept link redirects:
window.onbeforeunload = () => true;
document
.querySelectorAll("a")
.forEach((element) =>
element.addEventListener(
"click",
() => (window.onbeforeunload = null)
)
);
I don't know how to detect page reload, maybe by detecting F5 button is pressed or not? but this can't know if user manually click refresh button on browser.
Btw, you should really reconsider that why you would like to do that, cause if it's not for prevent users from lose their drafts, then I think it's not a user-friendly action.