웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

Notify user on browser close only

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.

Upvotes: 0

Views: 12094

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

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.

Upvotes: 5

SarathSprakash
SarathSprakash

Reputation: 4624

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

Upvotes: -1

Pratik
Pratik

Reputation: 29

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

Upvotes: 1

Roy M J
Roy M J

Reputation: 6938

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

Upvotes: 0

Related Questions