开发者

JavaScript alert on window.unload when browser is closed but should not alert when browser is refreshed

开发者 https://www.devze.com 2023-03-13 21:05 出处:网络
I want to popup a message in window.onunload event. Currently when user: a) navigates away开发者_JAVA技巧

I want to popup a message in window.onunload event.

Currently when user:

a) navigates away

开发者_JAVA技巧 b) closes the window

c) presses F5 or

d) presses refresh button in browser tool bar

The alert will appear., but I need it to not alert when user clicks the browser tool bar refresh button.

We added conditions for not alerting when users presses F5 or navigates away but alert should also not appear when users clicks browser refresh button.

Any type of workarounds would be nice.


I can offer a way to know if the user clicked on a browser button (back, forward, closing browser, etc...). I couldn't find any way to figure out which button was clicked, But I hope it will help you.

To know if the user clicked on a browser button, follow these steps: 1. Register window.beforeunload event. 2. In the handler, check event.clientY. 3. If event.clientY is not defiend or event.clientY<0, then you know the user clicked a browser button.

For example:
(You probably will have to change the code to fit it to your problem)

function beforeUnloadHandler(eventArg)
{
   var _e = window.event || eventArg;

   // browser button click
   if (isNaN(_e.clientY) || _e.clientY < 0) 
   {
       // unload process will continue
       // and unload event will be fired
       return;
   }

   // a confirmation with 'test alert' text will appear
   // if the user clicks 'Cancel', the unload process will stop 
   // and unload event won't be fired.
   return "test alert";
}
window.onbeforeunload = beforeUnloadHandler;

This code will work in all major browsers: chrome, ff, ie9,ie8,ie7,ie6, opera 11, opera 10, safari 3,4,5.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号