开发者

javascript alert issue after page close

开发者 https://www.devze.com 2023-02-03 15:16 出处:网络
I am using onbeforeunload function to aler开发者_Python百科t the user before he closes his browser window. Currently the alert will be called if we close any tab of the browser.

I am using onbeforeunload function to aler开发者_Python百科t the user before he closes his browser window. Currently the alert will be called if we close any tab of the browser.

I just need this functionality to be:

1) Alert before only when our tab is trying to close, ie this alert will not show when we try to close other tabs.

2) Should show when we try to close the whole browser using close button top right-end corner..

the below code works with jquery, th only problem that I am now facing in Mozilla firefox is, if there is any links present in that page like href to www.google.com, it will show the alert...in that case also, which is not needed. This works in IE, I am using mozilla 3.6

Please help.....

code below

<html>
<script src="jquery.js"></script>
<script>
$(function() {
    $(window).bind("beforeunload", function(e) {
      return "Are you sure?"
    });
  });

</script>

<body>
hiiiiii


</body>

</html>


Unfortunatly, there is no information in the event object (not yet). So you don't know how the user wants to leave your page. But you could work around this issues. For instance, you want to allow all external links to leave your site, you add some boolean flag.

var allowunload = false;


$('a').bind('click', function() {
    allowunload = true;
});

...And check for that in the beforeunload event:

$(window).bind('beforeunload', function(e) {
    if(!allowunload)
        return 'sure?';
});

See this in action: http://www.jsfiddle.net/4yUqL/41/


You can try the following:

$("a").click(function(){
   $(window).unbind('beforeunload');
});
$(window).bind('beforeunload', function(e) {
   return 'sure?';
});

This will unbind the event if the user clicks on an anchor. It has a small side effect though, if the anchor doesn't redirect to another page, but instead does some JavaScript functionality.

0

精彩评论

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

关注公众号