-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwindowService.js
387 lines (320 loc) · 10.9 KB
/
windowService.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
(function( context ){
var _domain = 'http://' + window.location.host;
var _messageHandlers = [];
var _childMessageHandlers = [];
var _childMessageSubjectHandlers = [];
var _windowUnloadHandlers = [];
var _parentWindowIdentifier = '__ParentWindow__';
var _parentKeyReference = '__ParentWindowKeyReference__';
var _initialisedSubject = '__windowInitialised__';
function getParentWindow(){
return window[_parentWindowIdentifier];
}
var _childWindowCollection = (function(){
var _dict = {};
var _onLoad = {};
var _key = 0;
return {
registerWindow : function( childWindow ){
_key++;
_keyReference = _key / 1;
_dict[ _keyReference ] = childWindow;
return {
getKey : function(){
return _keyReference;
},
registerOnLoadHandlers : function( callbackArray ){
_onLoad[ _keyReference ] = callbackArray;
}
};
},
removeWindowReference : function( key ){
delete _dict[ key ];
delete _onLoad[ _keyReference ];
},
registerWindowInitilisation : function( key ){
var childWindow = this.getWindow( key );
var handlers = this.getWindowOnLoadHandlers( key );
for( var i in handlers ){
handlers[i].call( null, childWindow );
}
},
getWindow : function( key ){
return _dict[ key ];
},
getWindowOnLoadHandlers : function( key ){
return _onLoad[ key ];
}
};
})();
// handles post messages sent to THIS window
window.addEventListener('message', function( message ) {
var subject = message.data.subject;
var data = message.data.data;
var key = message.data.key;
var origin = message.origin;
var sourceWindow = message.source;
// ignore the message if it does not originate from the same domain
if( origin !== _domain ){
return;
}
// check if it's a child window initialise message
if( subject === _initialisedSubject ){
return onChildWindowInitialised( data );
}
// invoke any generic message handlers
for ( var i in _messageHandlers ) {
var handler = _messageHandlers[i];
if ( handler.subject === subject ) {
handler.callback( data, subject, sourceWindow, key );
}
}
// invoke any messages handlers specific to child windows
for ( var j in _childMessageHandlers ) {
var childHandler = _childMessageHandlers[j];
if( childHandler.source !== sourceWindow ){
continue;
}
childHandler.callback( data, subject, sourceWindow, key );
}
// invoke any messages handlers specific to child windows with particular subjects
for ( var k in _childMessageSubjectHandlers ) {
var childSubjectHandler = _childMessageSubjectHandlers[k];
if( childSubjectHandler.source !== sourceWindow ){
continue;
}
if ( childSubjectHandler.subject === subject ) {
childSubjectHandler.callback( data, subject, sourceWindow, key );
}
}
});
function resolveWindowObject( childWindow ){
if( childWindow instanceof Window ){
return childWindow
}
if( typeof childWindow.getWindow === 'function' ){
return childWindow.getWindow();
}
throw new Error('Could not resolve the window object');
}
// adds message handlers to any messages that this window recives
function onMessage( subject, fn, context ){
if( typeof subject !== 'string' ){ throw new Error('Subject must be a string'); }
if( typeof fn !== 'function' ){ throw new Error('Message handler must be a function'); }
var callback = function( data, subject, sourceWindow, key ) {
fn.call(context || null, data, sourceWindow );
};
_messageHandlers.push({
subject: subject,
callback: callback
});
}
// adds message handlers to messages from a particular window
function whenMessagedBy( childWindow, fn, context ){
if( !childWindow ){ throw new Error('Expected a child window'); }
if( arguments.length === 1 ){
return {
withSubject : function( subject, handler, context ){
whenMessagedByWindowWithSubject( childWindow, subject, handler, context );
}
};
}
if( typeof fn !== 'function' ){ throw new Error('Message handler must be a function'); }
var callback = function( data, subject, sourceWindow, key ) {
fn.call(context || null, subject, data, sourceWindow );
};
_childMessageHandlers.push({
source : resolveWindowObject( childWindow ),
callback: callback
});
}
// adds message handlers to messages from a particular window with a particular subject
function whenMessagedByWindowWithSubject( childWindow, subject, fn, context ){
if( !childWindow ){ throw new Error('Expected a child window'); }
if( typeof subject !== 'string' ){ throw new Error('Subject must be a string'); }
if( typeof fn !== 'function' ){ throw new Error('Message handler must be a function'); }
var callback = function( data, subject, sourceWindow, key ) {
fn.call(context || null, data, sourceWindow );
};
_childMessageSubjectHandlers.push({
source : resolveWindowObject( childWindow ),
subject : subject,
callback: callback
});
}
// adds observers to the event that's fired when this window closes
function onParentWindowClose( fn ){
_windowUnloadHandlers.push( fn );
}
// now add the hook to notify all observers when this window closes
var _previousWindowUnloadHandle = ( typeof window.onbeforeunload === 'function' ? window.onbeforeunload : function(){} );
window.onbeforeunload = function(){
for( var i in _windowUnloadHandlers ){
try {
_windowUnloadHandlers[i].call( null, window );
} catch( e ){}
}
_previousWindowUnloadHandle();
};
// strategy for sending a message to an unspecified window
function messageWindow( windowObject, subject, data ){
if( typeof subject !== 'string' ){ throw new Error('Subject must be a string'); }
if( windowObject ){
windowObject.postMessage(
{ subject : subject, data : data },
_domain
);
}
}
// strategy to send message to parent window
function messageParentWindow( subject, data ){
return messageWindow( getParentWindow(), subject, data );
}
function onChildWindowInitialised( key ){
_childWindowCollection.registerWindowInitilisation( key );
}
// try message the parent to say that we've initialised
setTimeout( function(){
messageParentWindow( _initialisedSubject, window[ _parentKeyReference ] );
}, 10);
// our exposed interface below
context.windowService = {
// creates a child window - returns a childWindow interface
createWindow : function( options ){
if( !options ){ throw new Error('Options object must be provided.'); }
if( !options.url ){ throw new Error('Expected a url'); }
var childWindowReadyHandlers = [];
var childWindowUnloadHandlers = [];
var childWindowHasLoaded = false;
var childWindowIsOpen = true;
var closeChildWindowWhenParentCloses = options.closeWithParent || true;
var childWindow;
var childWindowKey;
var url = options.url;
var target = options.target || '_blank';
var windowOptions = {
'left' : 24,
'top' : 24,
'menubar' : 'no',
'toolbar' : 'no',
'location' : 0,
'resizable' : 'yes',
'scrollbars' : 'yes',
'status' : 'no',
'height' : options.height || window.innerHeight - 10,
'width' : options.width || window.innerWidth - 200,
'dependent' : 'yes',
'dialog' : 'no',
'chrome' : 'no',
'alwaysRaised' :'yes'
};
// convert our windows options into a string that the browser understands
var windowOptionsString = '';
for( var i in windowOptions ){
var prefix = ( windowOptionsString.length ? ',' : '' );
windowOptionsString += ( prefix + i + '=' + windowOptions[i].toString() );
}
childWindow = window.open( url, target, windowOptionsString );
var registeredWindow = _childWindowCollection.registerWindow( childWindow );
registeredWindow.registerOnLoadHandlers( childWindowReadyHandlers );
childWindowKey = registeredWindow.getKey();
// add reference to parent window
childWindow[_parentWindowIdentifier] = window;
childWindow[_parentKeyReference] = childWindowKey;
// strategy to send a message to the child window
function messageChildWindow( subject, data ){
return messageWindow( childWindow, subject, data );
}
// strategy to observe when child window has loaded
function onChildWindowReady( callback ){
childWindowReadyHandlers.push( function(){
callback.call( null, childWindow );
});
}
// inform THIS (parent) window if the child window closes
var _previousChildWindowUnloadHandle = ( typeof childWindow.onbeforeunload === 'function' ? childWindow.onbeforeunload : function(){} );
childWindow.onbeforeunload = function(){
for( var i in childWindowUnloadHandlers ){
try {
childWindowUnloadHandlers[i].call( null, childWindow );
} catch( e ){}
}
_previousChildWindowUnloadHandle();
};
// strategy to observe when the child window closes
function onChildWindowClose( fn ){
childWindowUnloadHandlers.push( fn );
}
// inform the child window if THIS (parent) window closes
onParentWindowClose( function( parentWindow ){
messageChildWindow('parentWindowClose');
if( closeChildWindowWhenParentCloses ){
childWindow.close();
}
});
onChildWindowClose( function(){
// indicate to consumers that the child window is now closed
childWindowIsOpen = false;
// remove the window reference from memory
_childWindowCollection.removeWindowReference( childWindowKey );
});
// allows service to indicate if child window has loaded
onChildWindowReady( function(){
childWindowHasLoaded = true;
});
// childWindow interface
return {
// returns the child window
getWindow : function(){
return childWindow;
},
// performs a callback once the window has loaded
then : function( fn ){
var root = this;
if( this.hasLoaded() ){
fn.call( null, root );
} else {
onChildWindowReady( function(){
fn.call( null, root );
});
}
return this;
},
// sends a message to the child window
message : messageChildWindow,
// indicates if the child window is open
isOpen : function(){
return childWindowIsOpen;
},
// indicates if the child window has loaded
hasLoaded : function(){
return childWindowHasLoaded;
},
// observe when the child window closes
onClose : onChildWindowClose,
// closes the child window
close : function(){
childWindow.close();
},
// keeps the child window open in the event of the parent window closing
keepOpen : function(){
closeChildWindowWhenParentCloses = false;
},
// gain focus
focus : function(){
this.getWindow().focus();
}
};
},
// observes when messages are received
onMessage : onMessage,
// observes when messages are received from a particular window
whenMessagedBy : whenMessagedBy,
// indicates if THIS window is a child
isChildWindow : function(){
return !!getParentWindow();
},
// sends a message to the parent window
messageParent : messageParentWindow
};
})( this );