tags:

views:

2912

answers:

9

hi,

After being through numerous forums available on the net for last 5 days, I am still not able to completely track down the browser close event. My requirement is to generate a popup message, when user tries to close the browser.

I have called my javascript function on body 'onbeforeunload' event. And I have hardcoded the conditions to check the mouse-coordinates for the red 'X' buton of browser, refresh, File-close or Alt-F4.

My code works fine when browser window is Maximized, but fails if we shrink it after a limit. Please help me, if some body has already found the solution to a similar problem.

Thank you.

Aggregated Responses of OP


Ok, just tell me if it is possible to detect if a user has clicked on the Refresh button of the browser. Also, Refresh can be triggered by Right-click - Refresh or Ctrl-R. My requirement is to make a variable false on Refresh. I am just able to do it on F5, but all other ways are still out of my reach. The same would be applied to Back buton.


Hi ppl, Thanks for all who replied atleast. I have talked to my seniors regarding this and they have now understood and have compromised with the browser menu buttons. So now my task has become easy. Now, I am using a variable and making it true by default. As, I mentioned earlier I just have to catch the onbeforeunload and popup a message when user tries to leave. The message will not popup when user is navigating to other pages, as I have made the variable as false on all the links of my page using following piece of code:

document.onclick = function() {
    //To check if user is navigating from the page by clicking on a hyperlink.
    if (event.srcElement.tagName == 'A')
        blnShowMsg = false; //To not popup the warning message
    else
        blnShowMsg = true; //To popup the warning message
}

In my case still the message is shown when user does Refresh, back or goes to any link in Favorites, etc.


Thanks buddy, but I have already gone through that and didn't find much help there too. My seniors are not happy with that solution as putting a flag on evry link of my application is a complicated job and they fear of breaking the application. Any other suggestions would be appreciated. Thanks once again.


Is there no one who can think of a solution here!!! where are all the experts???

+10  A: 

The question isn't an unusual one. Yet after 5 days searching the internet you still haven't found a satisfactory answer. That in itself should be a fairly plain indicator.

What I've found on the web is there is a serious aversion to the 'no can do' answer. When something can't be done the normal response is to make no response.

Bottom line is not only can what you are trying do not be done it should not be done.

I think you need to go back to your seniors and explain to them that a Web UI is a guest hosted by a browser on a client machine. This guest status is an important one.

Would you want a guest in your home to have the power to enforce you to alert them when you want to go to the toilet? No?

Similarly the browser limits what info the guest UI is allowed to access. Even if you found a workaround for the fact that browsers aren't giving up this info voluntarily, such clever hacks are fragile and likely to be constant source of bugs.

Since its likely that the application was originally intended to be delivered via the browser before any code was cut, the fault lies with including the requirement in the first place.

All we can do sympathise with you in being asked to perform an near impossible and certainly not sensible requirement.

AnthonyWJones
A: 

[ Moved to question ]

A: 

I believe there was some ways to do this in some browsers (and probably not very reliably) some years ago. Because I remember those awful massive spam-popups that spawned more popups as you closed one. But that's why it's not a good idea to allow scripts to detect this, and why browsers should prevent it and most modern browsers probably does.

I was asked to do something similar for a survey invitation script; they wanted to ask the visitor if they would like to answer a survey about their website, and then the survey should pop up when they leave the site. The solution I found was to (repeatedly) explain the management that this was probably impossible, or at best very unreliable; and instead the survey should popup immediately (if the visitor agreed to take the survey) and the intro page should tell the visitor to leave this window open and go back to it after reviewing the page.

Stein G. Strindhaug
A: 

[ Moved to Question ]

+1  A: 

In your function:

document.onclick = function()
    {
        //To check if user is navigating from the page by clicking on a hyperlink.
        if (event.srcElement.tagName == 'A')
         blnShowMsg = false; //To not popup the warning message
        else
         blnShowMsg = true;    //To popup the warning message
    }

blnShowMsg will be true for any click on your page except sometimes when the user click a link. I say sometimes because if event.srcElement.tagName doesn't work in some browser it will allways be true. And you have to add lots of cases to to allow using form controls etc... Some browsers can even automatically reload a page, and I'm not sure if onload events will run then or not.

But popping a warning about leaving the page (or similar) all the time is sure to annoy a lot of people, and they'll probably leave permanently...

If you're making for instance a online program where it's critical that something is saved before leaving, I'll say that catching the before unload event is a little too late, better to make some kind of autosave (see Gmail) and/or some kind of non-obtrusive warning when the user mouseover the navigation menues without saving.

But you can't force stupid users not to do anything stupid, on a web interface this is even more true because you have less controll: if the user want to terminate the program before saving they will find a way to do so, and they will call you and complain when the unsaved data dissapears ;P

Stein G. Strindhaug
Where does `event` come from?
The Elite Gentleman
I just prettyprinted the code from the question. I assume it was just dummy code to illustrate or that the code for getting the event object was removed for brevity.
Stein G. Strindhaug
+1  A: 

I have a method that is a bit clunky but it will work in most instances.

Create a "Holding" popup page containing a FRAMESET with one, 100% single FRAME and place the normal onUnload and onbeforeUnload event handlers in the HEAD.

<html>
<head>
<script language="Javascript" type="text/javascript">
  window.onbeforeunload = exitCheck;
  window.onunload = onCloseDoSomething;

  function onCloseDoSomething()
  {
  alert("This is executed at unload");
  }

  function exitCheck(evt)
  {
  return "Any string here."}
  </script>
  </head>

    <frameset rows="100%">
    <FRAME name="main" src="http://www.yourDomain.com/yourActualPage.aspx"&gt;
    </frameset>
<body>
</body>
</html>

Using this method you are free to use the actual page you want to see, post back and click hyperlinks without the outer frame onUnload or onbeforeUnload event being fired.

If the outer frame is refreshed or actually closed the events will fire.

Like i said, not full-proof but will get round the firing of the event on every postback.

Kevin Dark
A: 

"Thanks buddy, but I have already gone through that and didn't find much help there too. My seniors are not happy with that solution as putting a flag on evry link of my application is a complicated job and they fear of breaking the application. Any other suggestions would be appreciated. Thanks once again."

If you use jQuery, you can add link flags automatically. The way I would handle your problem is when the user performs the "dangerous" actions, iterate all the page links that are "dangerous" and then bind events to them.

$("#dangerbutton").click(function(){ 
  $("a").not( safeList ).click(function()
  {
     var dest = $(this).attr('href');
     someWarningFunction(function(){ 
         /* Stay where we are because user opted to stay */
     },function(){ 
         /* Continue Following Link because user didn't mind */
         window.location= dest; 
     });
     return false;
  });
});

This way will only fire on link clicks on your page. Users have to get used to the fact that "close window == cancel everything" logic, because many use and trust that facility.

Kent Fredric
A: 

You might have seen in many of the web form pages to warn the user before closing the page.When somebody refreshes the page, then there is a chance for loosing all filled data. In that case it is very helpful.

Page life cycle includes two events like onunload and onbeforeunload. For this case you need to bind the script function in window. Onbeforeunload so that it will be called when page is unloading.

Again this warning should not be fired when you are actually submitting the page. For that set a boolean value (e.g. shouldsubmit) to submit the page.

eliza sahoo