Reputation: 277
The scenario I have is a bit complicated, but I can reproduce my problem shortly in the following example:
<html>
<head>
<script type="text/javascript">
function fnUnloadHandler() {
alert("Unload event.. session termination request to be sent to server");
}
function f() {
i = 1;
while(1==1){
i++;
}
}
</script>
</head>
<body onbeforeunload="fnUnloadHandler()">
<p><button href="#" onClick="f();" >do</button></p>
</body>
</html>
Now; once the "do" button is clicked, f() get's the browser in an infinite loop. during that time if I close the page I get two different behaviours :
I would like to know why IE9 is not handling the onbeforeunload correctly in this case .. is there any fix/patch to apply to IE9 to fix this problem?
Many thanks in advance!
Firas
Upvotes: 1
Views: 1049
Reputation: 76405
JavaScript is, at least most, if not all, of its implementations are single-threaded. If you call the f
function, which contains an infinite loop, that one JS thread is busy. The onbeforeunload
handler is queued, and it will be called when the function f
returns. Unfortunately, f
will never return. Some implementations, though, pick up on constructs like while(1==1)
, and will terminate that loop, because it's not going anywhere. IE often presents you with a conform
alert, saying something along the lines of "A script is running, and doesn't look like it's getting anywhere, do you wish to terminate it?"
The only reason, logically, why the onbeforeunload
handler will get called is that if either the f
function is not called, or if the implementation of a specific browser won't just ditch the call queue when an error is encountered, and the handler will be called, still.
As an asside, some code-review:
function f()
{
i = 1;
}
is creating an evil implied global variable, change it to:
function f()
{
var i = 1;
}
to avoid cluttering the global namespace. Also, the onbeforeunload
event is generally attached to the global object, lest you want to handle the unload of a specific element. If you want to handle a global unload (client leaving the page), IE7 and IE8 will leak memory, check the solution here, that code example shows how you can avoid leaking memory with event handlers attached to the global object.
Upvotes: 2
Reputation: 73
Please see this link http://msdn.microsoft.com/en-us/library/ie/ms536907%28v=vs.85%29.aspx I hope this will help you
<!DOCTYPE html>
<html>
<head>
<script>
function closeIt()
{
return "any string";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
<a href="http://www.microsoft.com">Click here to navigate to
www.microsoft.com</a>
</body>
</html>
Upvotes: 1