0

I am trying to implement notifying when the user closes or reloades the page.Crrently i am using the following code

function unloadPage(){
    return "Your changes will not be saved.";
}
window.onbeforeclose = unloadPage;

This works fine.But the problem is this happens whenever a navigation takes place.That is either a page refresh or a form submission or a hyperlink click or whatever navigation takes place..I just want to work this code only for browser refreshing and closing.I knew about setting a flag and checking it. But i have to integrate this in a big application.So it will be difficult to add the code in every page.So is there an easy way. Is there a way to catch the refresh or browser cosing so that can use it.

웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
  • You can't catch a browser close request. However, you *can* remove the onbeforeunload handler when you know that the form is going to be submitted, or when a link is clicke.d – Rob W Aug 19 '13 at 09:32

4 Answers4

5

Note that in your code, you're using onbeforeclose, but the event name is beforeunload, so property is onbeforeunload, not onbeforeclose.

I just want to work this code only for browser refreshing and closing. Is there a way to catch the refresh or browser cosing so that can use it.

No. Instead, you'll have to capture each link and form submission and either set a flag telling your onbeforeunload handler not to return a string, or removing your onbeforeunload handler (probably the flag is cleaner).

For example:

var warnBeforeClose = true;
function unloadPage(){
    if (warnBeforeClose) {
        return "Your changes will not be saved.";
    }
}
window.onbeforeunload = unloadPage;

// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
    // Don't warn
    warnBeforeClose = false;

    // ...but if we're still on the page a second later, set the flag again
    setTimeout(function() {
        warnBeforeClose = true;
    }, 1000);
}

Or without setTimeout (but still with a timeout):

var warningSuppressionTime = 0;
function unloadPage(){
    if (+new Date() - warningSuppressionTime > 1000) { // More than a second
        return "Your changes will not be saved.";
    }
}
window.onbeforeunload = unloadPage;

// ...when the elements exist:
$("a").click(dontWarn);
$("form").submit(dontWarn);
function dontWarn() {
    // Don't warn for the next second
    warningSuppressionTime = +new Date();
}

Update in 2017: Also note that as of at least a couple of years ago, browsers don't show the message you return; they just use the fact you returned something other than null as a flag to show their own, built-in message instead.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • But i have to integrate this in a big application.So it will be difficult to add the code in every page.So is there an easy way. – 웃웃웃웃웃 Aug 19 '13 at 09:34
  • 3
    @User016: This *is* the easy way. You already have code on every page. Presumably that code is centralized (in some file included on each page). If not, centralize it so you're not repeating code all over the place. Then just add the above to the centralized code. – T.J. Crowder Aug 19 '13 at 09:37
  • I have followed the first method you suggested.But it fails in some cases and i dont know why.One is in the case of so redirection happening in a button click.I dont want to notify those times so i added `$("button").on('click',dontWarn);` in the code.But sometimes if fails and the alert is produced.Do you have some suggestions – 웃웃웃웃웃 Aug 20 '13 at 09:22
  • @User016: Are your buttons really `button` elements? Not `input[type=button]`? – T.J. Crowder Aug 20 '13 at 09:22
  • ``.This is one those buttons where the code is not working – 웃웃웃웃웃 Aug 20 '13 at 09:25
  • @User016: Then that should work. You'll have to look at the handlers attached to the button, to see if they prevent other handlers from running. – T.J. Crowder Aug 20 '13 at 09:31
  • onbeforeclose doesnt even exist. The right way is onbeforeunload, no? – Rangel R. Morais Nov 26 '17 at 00:02
  • @RangelR.Morais: **Four years** and no one (including me) noticed that when copying the OP's code, I didn't fix the property he/she was using. At least I had the right one in the text. :-) Thanks! – T.J. Crowder Nov 26 '17 at 10:21
1

One of the simple solutions to your problem is to have a flag and then call your function only if the flag is valid. In this case , you can bind the anchor tags, F5 key and form submit button click to events that set the flag as false. So your alert bar will be visible only if the above cases don't happen :)

Here's the script:

var validNavigation = false;

function endSession() {
  // Browser or broswer tab is closed
  alert("bye");
}

function wireUpEvents() {

  window.onbeforeunload = function() {
      if (!validNavigation) {
         endSession();
      }
  }

  // Attach the event keypress to exclude the F5 refresh
  $(document).bind('keypress', function(e) {
    if (e.keyCode == 116){
      validNavigation = true;
    }
  });

  // Attach the event click for all links in the page
  $("a").bind("click", function() {
    validNavigation = true;
  });

  // Attach the event submit for all forms in the page
  $("form").bind("submit", function() {
    validNavigation = true;
  });

  // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
    validNavigation = true;
  });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
  wireUpEvents();  
});
Pratik
  • 29
  • 2
0

Check this link

It gives you information on how to handle onbeforeunload event.

The idea is to have a global flag on the page. When any change is done to the fields, this flag is set to true. When clicked on save button, then this flag needs to be set to false.

In the onbeforeunload event, check whether the flag is true, then show the message accordingly.

var needToConfirm = true;

window.onbeforeunload = confirmExit;
function confirmExit()
{
    if (needToConfirm)
    {
        // check on the elements whether any change has been done on the fields.
        // If any change has been done, then set message here.
    }
}

function saveClicked()
{
    needToConfirm = false;
}
Roy M J
  • 6,926
  • 7
  • 51
  • 78
-1

DEMO

(Run or refresh the fiddle to see the alert onbeforeunload() event message and click on the link "kk" ,it wont show onbeforeunload() event message. Try it in your webpage)

I have a solution for you, you don have to add onclick event to each tags and all.

Just add this to any where on your pages .

<input type="hidden" value="true" id="chk"/>

and add this code to your document head tag

<script>
window.onbeforeunload = confirmExit;
function confirmExit()
{
   if(document.getElementById("chk").value=="true")
   {
      return "Your changes will not be saved.";
   }
}

document.onclick = myClickHandler;
function myClickHandler() {
      document.getElementById("chk").value="false";
    }
<script>

Hope this helps

Thank you

웃웃웃웃웃
  • 11,829
  • 15
  • 59
  • 91
SarathSprakash
  • 4,614
  • 2
  • 19
  • 35
  • This only works if you do not have onclick event handlers on your elements. As soon as you do, chk value will be set to false and no confirmation will be shown. – Vladimir Kocjancic Nov 06 '15 at 13:05