I am trying to add an iframe
element to a container div:
<template>
<div class="container" lwc:dom="manual"></div>
</template>
JavaScript:
import { LightningElement } from 'lwc';
import PP from '@salesforce/resourceUrl/penpal'
initialised = false;
iframe;
container;
async renderedCallback() {
if (this.initialised) {
return;
}
this.initialised = true;
// load Penpal
await loadScript(this, PP).catch(error => console.error(error));
// get container
this.container = this.template.querySelector('div.container');
// create iframe
this.iframe = document.createElement('iframe');
this.iframe.src = 'https://x.visualforce.com/apex/page';
// HERE: I try and add the iframe to the DOM
// bind the iframe to Penpal
const connection = Penpal.connectToChild({
// The iframe to which a connection should be made
iframe: this.iframe
});
}
Using the appendChild
method:
this.container.appendChild(this.iframe);
I get this error:
appendChild is not a function
Using the innerHTML
approach:
this.container.innerHTML = this.iframe.outerHTML;
I get this error:
Cannot add property innerHTML, object is not extensible
I also tried adding a DOMContentLoaded
event listener:
connectedCallback() {
window.addEventListener('DOMContentLoaded', function() {
this.container.appendChild(this.iframe);
}.bind(this), false);
}
But the DOMContentLoaded
event never fires?
Question
- What am I doing wrong?
- How can I get the iframe added to the DOM successfully?
iframe
in the template code like this<iframe src="https://x.visualforce.com/apex/page"></iframe>
, I get an error fromPenpal
saying theiframe
does not have asrc
set... andPenpal
documentation dynamically adds theiframe
... but I am open any suggestions :-)lwc:dom="manual"
as per the docs... perhaps you need to push the JS into a static resource rather than embedded within the LWC component itself to avoid the LWC compiler from doing stuff to it?