I would like to execute a function before leaving page without showing a confirmation popup with Javascript only. I\'ve tried with the code below but it did
What you're doing there is definitely not going to do it. Comparing window.onbeforeunload
to true
at some arbitrary time doesn't even make sense.
What's with the commented out code at the end? If anything, you need to assign a function to onbeforeunload
:
var result = 'test';
window.onbeforeunload = function() {
result = 'test1';
alertmess();
}
function alertmess() {
alert(result);
}
However, the above only appears to work in IE. Please see @Bulk's comment and @Brandon Gano's answer.
This is an example of how you could handle the navigate away. Notice how a div appears a little before the navigation occurs.
window.onbeforeunload = function ()
{
$("#oi").append($('<div>This is the child DIV</div>'));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="theMainDiv">
The Main Div will receive another div before leaving the page
</div>
<button onclick="window.location.href='pageAway'">Navigate Away</button>