46

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; //} 
5
  • 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). Commented Feb 20, 2015 at 10:52
  • check this out stackoverflow.com/questions/17975068/… Commented Feb 20, 2015 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. Commented Feb 20, 2015 at 10:56
  • try my solution, I have tested at my local machine. Commented Feb 20, 2015 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 developer.mozilla.org/en-US/docs/Web/API/Window/… Commented Oct 7, 2022 at 17:20

8 Answers 8

10

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for that. It works as your sample. However, it doesn't work as my desire. 1+ with that.
5

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; } 

Comments

4

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 } 

3 Comments

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.
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.
That said, I made an edit to my answer, as the return false will also prompt the user.
2

'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"); }); 

Comments

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.

1 Comment

The event name is "beforeunload" if using window.addEventListener(): window.addEventListener('beforeunload', function(e) {});
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.

2 Comments

I've tried with you code with FF and Chrome also. However, nothing happened.
@PMay1903 Yes, that's why I said "However, the above only appears to work in IE."
-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>

1 Comment

The code is on HTML section. Try testing it in the JS section.
-1

I simple put this code and works preety well

window.onbeforeunload = function(event) { $('element').show(); return; }; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.