views:

393

answers:

3

I have a function that is suppose to trigger when user closes their browser and I have put the code in the "window.onbeforeunload" function.

The thing is every time if I reloads the page in Internet Explorer, the onbeforeunload event will also trigger which is a problem because I only wants it to trigger only when the user closes or navigates away from the current page but not on a page refresh/reload.

Therefore I'm not sure if onbeforeunload is intended to trigger even on a page refresh/reload and if it is intended to, then is there another way to work round it? Thanks

A: 

There's no smart way to work around it. Any unloading action on the page will fire the unload and beforeunload events and there's no way to tell the difference between a refresh and a navigation.

You could attempt a couple of things, but there's no 100% method. For instance, capturing the F5 or Ctrl+R keys would identify a refresh, for which you could unset the onbeforeunload handler, but it would not work for users who click the refresh/reload button on their toolbar. You could attach an event handler to all clicks on an <a> element or any <form> onsubmits, but this wouldn't help for users who type a new address into the address bar from your page.

Andy E
+1  A: 

Since you are relying on javascript as it is, you may want to look into resolving the issue as to why they have to refresh the page. You can use XMLHttprequest to refresh the content for them so that the desired onbeforeunload function is only called when it needs to be.

John
A: 

Even if you use XMLHttprequest to refresh, IE has a problem. You have to call the javascript function that contains the XMLHttprequest, for example,

<a href="javascript:void(0)" onclick="addContent();">click to add content</a> 

will trigger an onbeforeunload event on IE, but not on Safari or Firefox.

One solution that'll work in some situations is to handle the event conditionally, turning it off when you want to load content then turning it back on

var guard = true; 
function myOnbeforeunloadHandler() 
{   
    if(guard)
    {
        return "you are about to leave the page and lose data";
    } 
}

function addContent()
{
    getElementById("myDiv").html = "<p>some content</p>";
    guard = true;
}

<a href="javascript:void(0) onclick="guard=false;addContent();> click to add content</a>
mrblasto