Template renderer init update (#1772)

* Update TemplateRendererFrameApi to post a 'ready' message

* Wait for 'ready' message rather than using 'load' event
This commit is contained in:
toasted-nutbread 2021-06-27 18:16:21 -04:00 committed by GitHub
parent 002da9fba8
commit 32d5fccc36
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 7 deletions

View File

@ -27,6 +27,7 @@ class TemplateRendererFrameApi {
prepare() { prepare() {
window.addEventListener('message', this._onWindowMessage.bind(this), false); window.addEventListener('message', this._onWindowMessage.bind(this), false);
this._postMessage(window.parent, 'ready', {}, null);
} }
// Private // Private
@ -52,7 +53,7 @@ class TemplateRendererFrameApi {
} }
if (typeof id === 'undefined') { return; } if (typeof id === 'undefined') { return; }
source.postMessage({action: `${action}.response`, params: response, id}, '*'); this._postMessage(source, `${action}.response`, response, id);
} }
_onRender({template, data, type}) { _onRender({template, data, type}) {
@ -101,4 +102,8 @@ class TemplateRendererFrameApi {
_clone(value) { _clone(value) {
return JSON.parse(JSON.stringify(value)); return JSON.parse(JSON.stringify(value));
} }
_postMessage(target, action, params, id) {
return target.postMessage({action, params, id}, '*');
}
} }

View File

@ -67,31 +67,33 @@ class TemplateRendererProxy {
_loadFrame(frame, url, timeout=5000) { _loadFrame(frame, url, timeout=5000) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let ready = false;
const cleanup = () => { const cleanup = () => {
frame.removeEventListener('load', onLoad, false); window.removeEventListener('message', onWindowMessage, false);
if (timer !== null) { if (timer !== null) {
clearTimeout(timer); clearTimeout(timer);
timer = null; timer = null;
} }
}; };
const onLoad = () => { const onWindowMessage = (e) => {
if (!ready) { return; } const frameWindow = frame.contentWindow;
if (frameWindow === null || frameWindow !== e.source) { return; }
const {data} = e;
if (!(typeof data === 'object' && data !== null && data.action === 'ready')) { return; }
cleanup(); cleanup();
resolve(); resolve();
}; };
let timer = setTimeout(() => { let timer = setTimeout(() => {
timer = null;
cleanup(); cleanup();
reject(new Error('Timeout')); reject(new Error('Timeout'));
}, timeout); }, timeout);
frame.removeAttribute('src'); frame.removeAttribute('src');
frame.removeAttribute('srcdoc'); frame.removeAttribute('srcdoc');
frame.addEventListener('load', onLoad, false); window.addEventListener('message', onWindowMessage, false);
try { try {
document.body.appendChild(frame); document.body.appendChild(frame);
ready = true;
frame.contentDocument.location.href = url; frame.contentDocument.location.href = url;
} catch (e) { } catch (e) {
cleanup(); cleanup();