34

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; 
//}
PMay 1903
  • 983
  • 2
  • 13
  • 28
  • 1
    The short answer is you can't do this. The `onbeforeunload` event can *only* be used to trigger that popup, it can't be used for anything else. Your only options for something like this are to attach an event to every outbound link on your page. However, there is no way to directly capture an event for someone leaving via other means (manually typing a url, closing the tab etc). – Dan Smith Feb 20 '15 at 10:52
  • check this out http://stackoverflow.com/questions/17975068/calling-js-functions-on-browser-tab-close – Jitendra Pancholi Feb 20 '15 at 10:55
  • I am looking for a way that it can trigger any function when a user is on the way to loading a new page or leaving the current page. – PMay 1903 Feb 20 '15 at 10:56
  • try my solution, I have tested at my local machine. – Jitendra Pancholi Feb 20 '15 at 11:22

8 Answers8

62

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.');
});
Jitendra Pancholi
  • 7,398
  • 9
  • 42
  • 79
  • 1
    That's great. Thank you for your code. It worked with function `myfun()`. Is there any way to disable the confirmation popup or using `alert()` instead of that? – PMay 1903 Feb 20 '15 at 12:24
  • 1
    Ok, in that case, write alert(''); in the myfun in the end, this would give you an error in js "NS_ERROR_NOT_AVAILABLE: " and confirmation popup wont come up, although it's wrong way to do it but will do the trick too ;-) – Jitendra Pancholi Feb 20 '15 at 12:40
  • `function myfun(){ // Write your business logic here console.log(result); alert(''); }` Is that correct? – PMay 1903 Feb 20 '15 at 13:02
  • 4
    Chrome 51 and above has disabled the custom message on `window.onbeforeunload` event – Faizan Akram Dar Jul 25 '16 at 10:30
  • I am using window.onbeforeunload = function() { xyz(); return 'sdfdfsadsfdf'; } But it never called the finction xyz() and sometimes its working, sometimes its not. Please help!! – Adarsh Singh Nov 06 '19 at 06:50
5

Just call your function from within window.onbeforeunload. Note, some browsers restrict what you can do here (eg: no redirects or alerts). See: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload for more info.

I've also added the appropriate code for readers that do want to show a confirmation dialog.

function doSomething(){
    //do some stuff here. eg:
    document.getElementById("test").innerHTML="Goodbye!";
}
function showADialog(e){
    var confirmationMessage = 'Your message here';
    //some of the older browsers require you to set the return value of the event
    (e || window.event).returnValue = confirmationMessage;     // Gecko and Trident
    return confirmationMessage;                                // Gecko and WebKit
}
window.addEventListener("beforeunload", function (e) {
    //To do something (Remember, redirects or alerts are blocked here by most browsers):
    doSomething();    
    //To show a dialog (uncomment to test):
    //return showADialog(e);  
});

Just hit 'Run' to test: http://jsfiddle.net/2Lv4pa9p/1/

Moob
  • 13,971
  • 1
  • 32
  • 45
1

If you want to prompt the user, return a string with the message. If you don't want to prompt the user, don't return anything.

// Execute code, then prompt the user to stay
window.onbeforeunload = function () {
  // This will happen before leaving the page
  return 'Are you sure you want to leave?';
}

Or:

// Execute code, then leave
window.onbeforeunload = function () {
  // This will happen before leaving the page
}
Brandon Gano
  • 5,960
  • 1
  • 22
  • 23
  • `window.onbeforeunload = function () { alert(result); // This will happen before leaving the page return false; }` I've tried with alert() before `return false;` as my thinking, but it doesn't work. – PMay 1903 Feb 20 '15 at 11:05
  • Browsers do not allow you to use `alert` in this handler. The only way to show a message is to return it as a string which gives the user the choice to stay or leave. – Brandon Gano Feb 20 '15 at 19:53
  • That said, I made an edit to my answer, as the `return false` will also prompt the user. – Brandon Gano Feb 20 '15 at 19:54
1

The documentation here encourages listening to the onbeforeunload event and/or adding an event listener on window.

window.addEventListener('onbeforeunload', function(e) {}, false);

You can also just populate the .onunload or .onbeforeunloadproperties of window with a function or a function reference.

Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.

davejoem
  • 4,206
  • 3
  • 20
  • 30
  • The event name is "beforeunload" if using window.addEventListener(): `window.addEventListener('beforeunload', function(e) {});` – B.Z. Apr 08 '21 at 19:06
1

Please try below simple code -

Jquery Code Example -

$(window).on('beforeunload', function(){
  Func_ToInsert_Record();
  alert('Thanks And Bye!');
});

Javascript Code Example -

// Anonymous function 
window.onbeforeunload = function(event) {
  var message = '';
  if (window.event) {
    console.log(window.event);
    console.log(event.currentTarget.performance);
    console.log(event.currentTarget.performance.navigation);
    console.log(event.currentTarget.performance.navigation.type);
     
  } 
  
  event = event || window.event;
  event.preventDefault = true;
  event.cancelBubble = true;
  event.returnValue = message;
}
mplungjan
  • 155,085
  • 27
  • 166
  • 222
Heemanshu Bhalla
  • 3,372
  • 1
  • 25
  • 47
0

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.

JLRishe
  • 95,368
  • 17
  • 122
  • 158
-1

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>
ClayKaboom
  • 1,813
  • 1
  • 22
  • 42
VasaraBharat
  • 81
  • 15
-1

I simple put this code and works preety well

window.onbeforeunload = function(event) {
    $('element').show();
    return;
};
Gabriel Glauber
  • 921
  • 11
  • 9