Render a dynamically created button inside a dynamically created iframe and pass messages from the iFrame to parent

Viewed 22

So I have a button that's created dynamically and I want to render it inside another dynamically created iFrame. I'm trying the below code but that just renders the button in the following way:

enter image description here

const widgetButton =  document.createElement('button');
var iframe = document.createElement('iframe');

widgetButton.onclick = openWidget;
widgetButton.innerHTML = 'Hello';
iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(widgetButton);

Maybe I need to change the type in 'data:' in the src. But I'm not sure what that would be.

EDIT:

I tried the following as well. But this time openWidget remains undefined as expected. So is there as way I can inject this function (may be injecting <script> inside this iFrame?

        var html = `<button onclick="openWidget()">HEllo</button>`;
        
        iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);

        document.body.appendChild(iframe);
1 Answers
const html = `<script>
      function buttonClicked(){
      window.parent.postMessage("widgetButtonClicked", '*');
    }
</script>
<body>
       <button onclick="buttonClicked()">Widget</button>
</body>`;


const iframe = document.createElement('iframe');

iframe.src = 'data:text/html;charset=utf-8,' + encodeURI(html);

document.body.appendChild(iframe);

And then inside parent,

window.addEventListener("message", (event)=>{
   if(event.data === 'widgetButtonClicked'){
     openWidget()
   }
})
Related