Unload events only get handled when set up certain ways. Different browsers support different approaches, and no approach works with all browsers. The HTML 4.01 and DOM 2 specifications indicate that body and frameset elements get unload events. As detailed in the following table, no browser gets this completely right. ("x" indicates the test passed, "-" that it failed.) Following the table are a description of the results, then the tests themselves.

Browser Variant 1
(window.addEventListener();)
Variant 2
(window.onunload)
Variant 3
(body.addEventListener();)
Variant 4
(body.onunload)
Variant 5
(body.setAttribute("onunload");)
IE x - - - -
Konqueror x - x - x
Mozilla x - - - x
Opera x x x x x
Safari - - x x -

IE, Konqueror, Mozilla, and Opera all fire the unload event on the window object. While this is outside the domain of the HTML and DOM 2 specifications, this is the most widely supported approach. Only Opera supports setting window.onunload.

IE does not support the unload event on the body element. Konqueror, Mozilla, Opera, and Safari all fire the unload event for the body element, but each has quirks. Konqueror, Mozilla, and Safari do not support all three tested methods for establishing the handler. Opera does, but it also runs the handler multiple times.

At present, there is no single way to establish an unload handler that works on all the tested browsers. Ideally, all browsers would support all five scenarios tested. Safari should support the de facto window unload event handler (part of JavaScript since at least version 1.3), IE should support the standardized body and frameset unload event, and all browsers should allow the handler to be established using any of the methods used in the tests below.

All the tested browsers fire an exception (appropriately) if window.setAttribute() is called, so this approach is omitted from the table.

In each of the following tests, clicking the gray div should result in a single alert box popping up before a blank page (about:blank) is displayed.

Click to test unload variant 1

Variant 1 sets an unload event handler on the window using the DOM addEventListener() method. If addEventListener() is not available, it uses the IE attachEvent() method.

Click to test unload variant 2

Variant 2 sets the handler on the window by setting the window object's onload property.

Click to test unload variant 3

Variant 3 sets the handler on the body element using addEventListener() or attachEvent().

Click to test unload variant 4

Variant 4 sets the handler on the body element by setting the element's onload property.

Click to test unload variant 5

Variant 5 sets the handler on the body element by calling setAttribute() to set the element's onload property.