1 | 'use strict';
|
---|
2 |
|
---|
3 | var random = require('./random');
|
---|
4 |
|
---|
5 | var onUnload = {}
|
---|
6 | , afterUnload = false
|
---|
7 | // detect google chrome packaged apps because they don't allow the 'unload' event
|
---|
8 | , isChromePackagedApp = global.chrome && global.chrome.app && global.chrome.app.runtime
|
---|
9 | ;
|
---|
10 |
|
---|
11 | module.exports = {
|
---|
12 | attachEvent: function(event, listener) {
|
---|
13 | if (typeof global.addEventListener !== 'undefined') {
|
---|
14 | global.addEventListener(event, listener, false);
|
---|
15 | } else if (global.document && global.attachEvent) {
|
---|
16 | // IE quirks.
|
---|
17 | // According to: http://stevesouders.com/misc/test-postmessage.php
|
---|
18 | // the message gets delivered only to 'document', not 'window'.
|
---|
19 | global.document.attachEvent('on' + event, listener);
|
---|
20 | // I get 'window' for ie8.
|
---|
21 | global.attachEvent('on' + event, listener);
|
---|
22 | }
|
---|
23 | }
|
---|
24 |
|
---|
25 | , detachEvent: function(event, listener) {
|
---|
26 | if (typeof global.addEventListener !== 'undefined') {
|
---|
27 | global.removeEventListener(event, listener, false);
|
---|
28 | } else if (global.document && global.detachEvent) {
|
---|
29 | global.document.detachEvent('on' + event, listener);
|
---|
30 | global.detachEvent('on' + event, listener);
|
---|
31 | }
|
---|
32 | }
|
---|
33 |
|
---|
34 | , unloadAdd: function(listener) {
|
---|
35 | if (isChromePackagedApp) {
|
---|
36 | return null;
|
---|
37 | }
|
---|
38 |
|
---|
39 | var ref = random.string(8);
|
---|
40 | onUnload[ref] = listener;
|
---|
41 | if (afterUnload) {
|
---|
42 | setTimeout(this.triggerUnloadCallbacks, 0);
|
---|
43 | }
|
---|
44 | return ref;
|
---|
45 | }
|
---|
46 |
|
---|
47 | , unloadDel: function(ref) {
|
---|
48 | if (ref in onUnload) {
|
---|
49 | delete onUnload[ref];
|
---|
50 | }
|
---|
51 | }
|
---|
52 |
|
---|
53 | , triggerUnloadCallbacks: function() {
|
---|
54 | for (var ref in onUnload) {
|
---|
55 | onUnload[ref]();
|
---|
56 | delete onUnload[ref];
|
---|
57 | }
|
---|
58 | }
|
---|
59 | };
|
---|
60 |
|
---|
61 | var unloadTriggered = function() {
|
---|
62 | if (afterUnload) {
|
---|
63 | return;
|
---|
64 | }
|
---|
65 | afterUnload = true;
|
---|
66 | module.exports.triggerUnloadCallbacks();
|
---|
67 | };
|
---|
68 |
|
---|
69 | // 'unload' alone is not reliable in opera within an iframe, but we
|
---|
70 | // can't use `beforeunload` as IE fires it on javascript: links.
|
---|
71 | if (!isChromePackagedApp) {
|
---|
72 | module.exports.attachEvent('unload', unloadTriggered);
|
---|
73 | }
|
---|