PMay 1903 PMay 1903 - 6 months ago 45
Javascript Question

How to call a function before leaving page with Javascript

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 didn't work or with the

onbeforeunload
but it always shows the popup.

var result = 'test';

if(window.onbeforeunload == true)
{
result = 'test1';
alertmess();
}

function alertmess() {
alert(result);
}

//window.onbeforeunload = function() {
// return result;
//}

Answer

You can always call your function before leaving the page.

function myfun(){
     // Write your business logic here
     console.log('hello');
}

onbeforeunload:

window.onbeforeunload = function(){
  myfun();
  return 'Are you sure you want to leave?';
};

Or with jQuery:

$(window).bind('beforeunload', function(){
  myfun();
  return 'Are you sure you want to leave?';
});

This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.

You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):

window.onunload = function() {
    myfun();
    alert('Bye.');
}

Or with jQuery:

$(window).unload(function(){
  myfun();
  alert('Bye.');
});