This repository has been archived by the owner on Jan 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpym.js
519 lines (436 loc) · 16.8 KB
/
pym.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/*! pym.js - v0.4.1 - 2014-12-12 */
/*
* Pym.js is library that resizes an iframe based on the width of the parent and the resulting height of the child.
* Check out the docs at http://blog.apps.npr.org/pym.js/ or the readme at README.md for usage.
*/
/* global module */
(function(factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = factory();
} else {
window.pym = factory.call(this);
}
})(function() {
var MESSAGE_DELIMITER = 'xPYMx';
var lib = {};
/**
* Generic function for parsing URL params.
* Via http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
*
* @method _getParameterByName
* @param {String} name The name of the paramter to get from the URL.
*/
var _getParameterByName = function(name) {
var regex = new RegExp("[\\?&]" + name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]') + '=([^&#]*)');
var results = regex.exec(location.search);
if (results === null) {
return '';
}
return decodeURIComponent(results[1].replace(/\+/g, " "));
};
/**
* Check the message to make sure it comes from an acceptable xdomain.
* Defaults to '*' but can be overriden in config.
*
* @method _isSafeMessage
* @param {Event} e The message event.
* @param {Object} settings Configuration.
*/
var _isSafeMessage = function(e, settings) {
if (settings.xdomain !== '*') {
// If origin doesn't match our xdomain, return.
if (!e.origin.match(new RegExp(settings.xdomain + '$'))) { return; }
}
return true;
};
/**
* Construct a message to send between frames.
*
* NB: We use string-building here because JSON message passing is
* not supported in all browsers.
*
* @method _makeMessage
* @param {String} id The unique id of the message recipient.
* @param {String} messageType The type of message to send.
* @param {String} message The message to send.
*/
var _makeMessage = function(id, messageType, message) {
var bits = ['pym', id, messageType, message];
return bits.join(MESSAGE_DELIMITER);
};
/**
* Construct a regex to validate and parse messages.
*
* @method _makeMessageRegex
* @param {String} id The unique id of the message recipient.
*/
var _makeMessageRegex = function(id) {
var bits = ['pym', id, '(\\S+)', '(.+)'];
return new RegExp('^' + bits.join(MESSAGE_DELIMITER) + '$');
};
/**
* Initialize Pym for elements on page that have data-pym attributes.
*
* @method _autoInit
*/
var _autoInit = function() {
var elements = document.querySelectorAll(
'[data-pym-src]:not([data-pym-auto-initialized])'
);
var length = elements.length;
for (var idx = 0; idx < length; ++idx) {
var element = elements[idx];
/*
* Mark automatically-initialized elements so they are not
* re-initialized if the user includes pym.js more than once in the
* same document.
*/
element.setAttribute('data-pym-auto-initialized', '');
// Ensure elements have an id
if (element.id === '') {
element.id = 'pym-' + idx;
}
var src = element.getAttribute('data-pym-src');
var xdomain = element.getAttribute('data-pym-xdomain');
var config = {};
if (xdomain) {
config.xdomain = xdomain;
}
new lib.Parent(element.id, src, config);
}
};
/**
* The Parent half of a response iframe.
*
* @class Parent
* @param {String} id The id of the div into which the iframe will be rendered.
* @param {String} url The url of the iframe source.
* @param {Object} config Configuration to override the default settings.
*/
lib.Parent = function(id, url, config) {
this.id = id;
this.url = url;
this.el = document.getElementById(id);
this.iframe = null;
this.settings = {
xdomain: '*'
};
this.messageRegex = _makeMessageRegex(this.id);
this.messageHandlers = {};
/**
* Construct the iframe.
*
* @memberof Parent.prototype
* @method _constructIframe
*/
this._constructIframe = function() {
// Calculate the width of this element.
var width = this.el.offsetWidth.toString();
// Create an iframe element attached to the document.
this.iframe = document.createElement("iframe");
// Save fragment id
var hash = '';
var hashIndex = this.url.indexOf('#');
if (hashIndex > -1) {
hash = this.url.substring(hashIndex, this.url.length);
this.url = this.url.substring(0, hashIndex);
}
// If the URL contains querystring bits, use them.
// Otherwise, just create a set of valid params.
if (this.url.indexOf('?') < 0) {
this.url += '?';
} else {
this.url += '&';
}
// Append the initial width as a querystring parameter, and the fragment id
this.iframe.src = this.url + 'initialWidth=' + width + '&childId=' + this.id + hash;
// Set some attributes to this proto-iframe.
this.iframe.setAttribute('width', '100%');
this.iframe.setAttribute('scrolling', 'no');
this.iframe.setAttribute('marginheight', '0');
this.iframe.setAttribute('frameborder', '0');
// Append the iframe to our element.
this.el.appendChild(this.iframe);
// Add an event listener that will handle redrawing the child on resize.
var that = this;
window.addEventListener('resize', function() {
that.sendWidth();
});
};
/**
* Fire all event handlers for a given message type.
*
* @memberof Parent.prototype
* @method _fire
* @param {String} messageType The type of message.
* @param {String} message The message data.
*/
this._fire = function(messageType, message) {
if (messageType in this.messageHandlers) {
for (var i = 0; i < this.messageHandlers[messageType].length; i++) {
this.messageHandlers[messageType][i].call(this, message);
}
}
};
/**
* @callback Parent~onMessageCallback
* @param {String} message The message data.
*/
/**
* Process a new message from the child.
*
* @memberof Parent.prototype
* @method _processMessage
* @param {Event} e A message event.
*/
this._processMessage = function(e) {
if (!_isSafeMessage(e, this.settings)) { return; }
// Grab the message from the child and parse it.
var match = e.data.match(this.messageRegex);
// If there's no match or too many matches in the message, punt.
if (!match || match.length !== 3) {
return false;
}
var messageType = match[1];
var message = match[2];
this._fire(messageType, message);
};
/**
* Resize iframe in response to new height message from child.
*
* @memberof Parent.prototype
* @method _onHeightMessage
* @param {String} message The new height.
*/
this._onHeightMessage = function(message) {
/*
* Handle parent message from child.
*/
var height = parseInt(message);
this.iframe.setAttribute('height', height + 'px');
this.iframe.style['height'] = height + 'px';
};
/**
* Bind a callback to a given messageType from the child.
*
* @memberof Parent.prototype
* @method onMessage
* @param {String} messageType The type of message being listened for.
* @param {Parent~onMessageCallback} callback The callback to invoke when a message of the given type is received.
*/
this.onMessage = function(messageType, callback) {
if (!(messageType in this.messageHandlers)) {
this.messageHandlers[messageType] = [];
}
this.messageHandlers[messageType].push(callback);
};
/**
* Send a message to the the child.
*
* @memberof Parent.prototype
* @method sendMessage
* @param {String} messageType The type of message to send.
* @param {String} message The message data to send.
*/
this.sendMessage = function(messageType, message) {
this.el.getElementsByTagName('iframe')[0].contentWindow.postMessage(_makeMessage(this.id, messageType, message), '*');
};
/**
* Transmit the current iframe width to the child.
*
* You shouldn't need to call this directly.
*
* @memberof Parent.prototype
* @method sendWidth
*/
this.sendWidth = function() {
var width = this.el.offsetWidth.toString();
this.sendMessage('width', width);
};
// Add any overrides to settings coming from config.
for (var key in config) {
this.settings[key] = config[key];
}
// Add height event callback
this.onMessage('height', this._onHeightMessage);
// Add a listener for processing messages from the child.
var that = this;
window.addEventListener('message', function(e) {
return that._processMessage(e);
}, false);
// Construct the iframe in the container element.
this._constructIframe();
return this;
};
/**
* The Child half of a responsive iframe.
*
* @class Child
* @param {Object} config Configuration to override the default settings.
*/
lib.Child = function(config) {
this.parentWidth = null;
this.id = null;
this.settings = {
renderCallback: null,
xdomain: '*',
polling: 0
};
this.messageRegex = null;
this.messageHandlers = {};
/**
* Bind a callback to a given messageType from the child.
*
* @memberof Child.prototype
* @method onMessage
* @param {String} messageType The type of message being listened for.
* @param {Child~onMessageCallback} callback The callback to invoke when a message of the given type is received.
*/
this.onMessage = function(messageType, callback) {
if (!(messageType in this.messageHandlers)) {
this.messageHandlers[messageType] = [];
}
this.messageHandlers[messageType].push(callback);
};
/**
* @callback Child~onMessageCallback
* @param {String} message The message data.
*/
/**
* Fire all event handlers for a given message type.
*
* @memberof Parent.prototype
* @method _fire
* @param {String} messageType The type of message.
* @param {String} message The message data.
*/
this._fire = function(messageType, message) {
/*
* Fire all event handlers for a given message type.
*/
if (messageType in this.messageHandlers) {
for (var i = 0; i < this.messageHandlers[messageType].length; i++) {
this.messageHandlers[messageType][i].call(this, message);
}
}
};
/**
* Process a new message from the parent.
*
* @memberof Child.prototype
* @method _processMessage
* @param {Event} e A message event.
*/
this._processMessage = function(e) {
/*
* Process a new message from parent frame.
*/
// First, punt if this isn't from an acceptable xdomain.
if (!_isSafeMessage(e, this.settings)) { return; }
// Get the message from the parent.
var match = e.data.match(this.messageRegex);
// If there's no match or it's a bad format, punt.
if (!match || match.length !== 3) { return; }
var messageType = match[1];
var message = match[2];
this._fire(messageType, message);
};
/**
* Send a message to the the Parent.
*
* @memberof Child.prototype
* @method sendMessage
* @param {String} messageType The type of message to send.
* @param {String} message The message data to send.
*/
this.sendMessage = function(messageType, message) {
/*
* Send a message to the parent.
*/
window.parent.postMessage(_makeMessage(this.id, messageType, message), '*');
};
/**
* Transmit the current iframe height to the parent.
*
* Call this directly in cases where you manually alter the height of the iframe contents.
*
* @memberof Child.prototype
* @method sendHeight
*/
this.sendHeight = function() {
/*
* Transmit the current iframe height to the parent.
* Make this callable from external scripts in case they update the body out of sequence.
*/
// Get the child's height.
body = document.getElementsByTagName('body')[0];
body.style["visibility"] = 'hidden';
//var height2 = document.getElementsByTagName('body')[0].offsetHeight.toString();
//var height = document.getElementsByTagName('body')[0].offsetHeight.toString();
var height = document.getElementsByTagName('body')[0].scrollHeight.toString();
/*
var html = document.getElementsByTagName('html');
var body = document.getElementsByTagName('body');
var height = Math.max(html.scrollHeight, html.offsetHeight, body.scrollHeight, body.offsetHeight);
*/
// Send the height to the parent.
that.sendMessage('height', height.toString());
body.style["visibility"] = 'visible';
};
/**
* Resize iframe in response to new width message from parent.
*
* @memberof Child.prototype
* @method _onWidthMessage
* @param {String} message The new width.
*/
this._onWidthMessage = function(message) {
/*
* Handle width message from the child.
*/
var width = parseInt(message);
// Change the width if it's different.
if (width !== this.parentWidth) {
this.parentWidth = width;
// Call the callback function if it exists.
if (this.settings.renderCallback) {
this.settings.renderCallback(width);
}
// Send the height back to the parent.
this.sendHeight();
}
};
// Identify what ID the parent knows this child as.
this.id = _getParameterByName('childId') || config.id;
this.messageRegex = new RegExp('^pym' + MESSAGE_DELIMITER + this.id + MESSAGE_DELIMITER + '(\\S+)' + MESSAGE_DELIMITER + '(.+)$');
// Get the initial width from a URL parameter.
var width = parseInt(_getParameterByName('initialWidth'));
// Bind the width message handler
this.onMessage('width', this._onWidthMessage);
// Initialize settings with overrides.
for (var key in config) {
this.settings[key] = config[key];
}
// Set up a listener to handle any incoming messages.
var that = this;
window.addEventListener('message', function(e) {
that._processMessage(e);
}, false);
// If there's a callback function, call it.
if (this.settings.renderCallback) {
this.settings.renderCallback(width);
}
// Send the initial height to the parent.
this.sendHeight();
// If we're configured to poll, create a setInterval to handle that.
if (this.settings.polling) {
window.setInterval(this.sendHeight, this.settings.polling);
}
return this;
};
// Initialize elements with pym data attributes
_autoInit();
return lib;
});