-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMirrorIframe.js
More file actions
74 lines (57 loc) · 2.16 KB
/
MirrorIframe.js
File metadata and controls
74 lines (57 loc) · 2.16 KB
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
class MirrorIframe extends HTMLElement {
constructor() {
super(); // Always call super first in constructor
const thisElem = this;
thisElem._emitEvents = true;
// Gets content from <template>
const shadow = thisElem.attachShadow({mode: 'open'});
shadow.innerHTML = `<style>
:host {
display: block;
height: 100%;
width: 100%;
}
</style>
<div style="display: block; width: 100%; height: 100%;">
<iframe scrolling="no" style="width: 1px; min-width: 100%; height: 1px; min-height: 100%; display:block; border: 0; padding: 0; margin: 0;"></iframe>
</div>`;
thisElem._elements = {};
thisElem._elements.iframe = shadow.querySelector('iframe');
// Emit messages passed from iFrame window
window.addEventListener('message', function(messageEvent) {
if(thisElem._emitEvents && thisElem._elements.iframeWindow === messageEvent.source && typeof messageEvent.data.event.type === 'string')
thisElem.emitMirror(messageEvent.data.tag, 'triggerEvent', [messageEvent.data.event])
});
}
connectedCallback() {
// Set iFrame src (willa lso be set when src attribute changes)
let thisElem = this;
thisElem._elements.iframe.onload = function() {
thisElem._elements.iframeWindow = thisElem._elements.iframe.contentWindow;
};
thisElem._elements.iframe.setAttribute('src', this.getAttribute('src'));
}
static get observedAttributes() {
return ['src'];
}
attributeChangedCallback(attr, oldVal, newVal) {
if(attr === 'src')
this._elements.iframe.setAttribute('src', newVal);
};
emitMirror(mirrorTag, functionName, functionArgs) {
if(typeof functionArgs == 'undefined')
functionArgs = [];
let emitMirrorDetail = {function: functionName, arguments: Array.prototype.slice.call(functionArgs)};
if(typeof mirrorTag != 'undefined')
emitMirrorDetail.tag = mirrorTag;
let event = new CustomEvent('mirror', {detail: emitMirrorDetail});
this.dispatchEvent(event);
};
triggerEvent(event, mirrorTag) {
this._emitEvents = false;
this._elements.iframeWindow.postMessage({event: event, tag: mirrorTag}, '*');
this._emitEvents = true;
};
}
customElements.define('mirror-iframe', MirrorIframe);
export default MirrorIframe;