views:

241

answers:

3

Hello all,

I have just been helped on a problem I have here.

var win = window.open(url, name);
win.onunload = StartLoad;
win.close();

To solve this problem completely, I wanted to know if onunload will be triggered once or every time a event occurs?

In other words, will my function startLoad run every time the child window "win" gets redirected, closed etc? Or will it do this event once and that's it?

Apologies, if this is a silly question.

Thanks all

+1  A: 

It should only fire once, the first time the window unloads. Anything else would be a security hole.

EricLaw -MSFT-
+2  A: 

No - this method can fire multiple times as you navigate off a page in IE6 and IE7.

This code snippet illustrates this (save as OnUnloadTest.htm):

<body>
    <form id="form" action="OnUnloadTest.htm" method="post">
     Click <a href="javascript:form.submit()">here</a>
    </form>
    <script type="text/javascript">
     window.onbeforeunload = beforeunload
     function beforeunload() {
      alert('OnUnload');
     }
    </script>
</body>

Basically, the event fires once for the actual anchor click, and once as the page actually posts back. I've only seen this issue when you have javascript in the href of the anchor, although if you use ASP.NET linkbuttons then be warned as this puts javascript in the href.

For most other sorts of navigation (e.g. user clicks a normal anchor, or closes the browser, or navigates away with a bookmark, etc) the event does only fire once.

Rob Levine
Wasn't the question about "unload" event, not "beforeunload" one?
kangax
A: 

Read WebKit Page Cache II – The unload Event for interesting discussion on how unload event plays with page caching feature of modern browsers.

Piotr Dobrogost