I want to make a confirmation before user leaving the page. If he says ok then it would redirect to new page or cancel to leave. I tried to make it with onunload
<
Just a bit more helpful, enable and disable
$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');
You can use the following one-liner to always ask the user before leaving the page.
window.onbeforeunload = s => "";
To ask the user when something on the page has been modified, see this answer.
<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">
<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>
<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>
<script>
function myFunction() {
return "Write something clever here...";
}
</script>
</body>
</html>
https://www.w3schools.com/tags/ev_onbeforeunload.asp
Most of the solutions here did not work for me so I used the one found here
I also added a variable to allow the confirm box or not
window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
if (!hideWarning) {
event.preventDefault();
event.returnValue = '';
}
});