42

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
  • 1,103
  • 3
  • 15
  • 31
  • 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
  • `According to the specification, to show the confirmation dialog an event handler should call preventDefault() on the event. The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML specification for more details`. from https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event – tabebqena Oct 07 '22 at 17:20

9 Answers9

68

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,897
  • 12
  • 51
  • 84
  • 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
  • 5
    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
  • @JitendraPancholi Is there a way to do this `WITHOUT` any popups? Like just run some code and let the user continue what they were doing without any permission? I'm making a game and I want to save progress before leaving, without asking for the user's confirmation. – Halo Jul 22 '22 at 11:40
  • Read my comment in the answer. I gave one trick to avoid alerts/confirmation box. – Jitendra Pancholi Jul 22 '22 at 12:06
  • Please edit your answer to include the fact that this will not work with asynchronous functions! – Silidrone Feb 23 '23 at 14:43
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
  • 14,420
  • 1
  • 34
  • 47
4

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
  • 169,008
  • 28
  • 173
  • 236
Heemanshu Bhalla
  • 3,603
  • 1
  • 27
  • 53
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
  • 6,430
  • 1
  • 25
  • 25
  • `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,902
  • 4
  • 22
  • 31
  • The event name is "beforeunload" if using window.addEventListener(): `window.addEventListener('beforeunload', function(e) {});` – B.Z. Apr 08 '21 at 19:06
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
  • 99,490
  • 19
  • 131
  • 169
0

'beforerunload' does not work anymore, you can use 'unload' event instead, even if it is not recommended, or 'visibilitychange' or 'hidepage' events as well.

window.addEventListener("visibilitychange", function(event) {
   
    console.log("hey");   
});
Bruno L.
  • 457
  • 6
  • 8
-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,833
  • 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
  • 961
  • 11
  • 9