diff --git a/components/page.js b/components/page.js index 1e5065b..e4069ef 100644 --- a/components/page.js +++ b/components/page.js @@ -16,16 +16,24 @@ const frameHtml = `
- ${'<'}script type="module"> -const frame = document.getElementsByTagName('iframe')[0] + let frame = undefined addEventListener('message', event => { + let isNew = false const d = event.data if (Array.isArray(d) && d[0] === 'srcdoc') { + isNew = frame === undefined + if (isNew) { + frame = document.createElement('iframe') + frame.sandbox = "allow-scripts allow-top-navigation" + } frame.srcdoc = d[1] - } else { + } else if (frame !== undefined) { frame.postMessage(event.data) } + if (isNew) { + document.body.appendChild(frame) + } }) ${''}script> @@ -88,30 +96,27 @@ export class Page extends HTMLElement { initFrame() { const wrap = document.createElement('div') this.shadowRoot.appendChild(wrap) - const tmp = document.createElement('iframe') + const frame = document.createElement('iframe') if (this.csp !== undefined) { - tmp.sandbox = "allow-same-origin allow-scripts allow-top-navigation" + frame.sandbox = "allow-same-origin allow-scripts allow-top-navigation" const url = new URL( '/-/frame', location.href ) url.searchParams.set('csp', this.csp) url.searchParams.set('html', frameHtml) - tmp.src = url.href + frame.src = url.href } else { - tmp.sandbox = "allow-scripts" - tmp.srcdoc = frameHtml + frame.sandbox = "allow-scripts allow-top-navigation" + frame.srcdoc = frameHtml } - wrap.insertAdjacentHTML( - 'beforeend', tmp.outerHTML - ) - const frames = wrap.getElementsByTagName('iframe') - this.frame = frames[frames.length - 1] + frame.addEventListener('load', () => { + this.display(this.body) + }) + wrap.appendChild(frame) + this.frame = frame this.textArea.addEventListener('blur', e => { this.display(e.target.value) }) - this.frame.addEventListener('load', () => { - this.display(this.body) - }) } display(value) {