Inject js code into iframe

by Amir Sharifian

HTML

<iframe id="myiframe" width="200" height="200" srcdoc="<h1 id='title'>Hello from Iframe</h1><button type='button' id='fire'>Click Me!</button>
"></iframe>

JavaScript

const iframe = document.getElementById('myiframe');
  const iframeWin = iframe.contentWindow || iframe;
  const iframeDoc = iframe.contentDocument || iframeWin.document;

  var script = iframeDoc.createElement("script");
  script.append(`
	window.onload = function() {
     document.getElementById("fire").addEventListener('click', function() {
        const text = document.getElementById('title').innerText;
        alert(text);
     })
  }
`);
  iframeDoc.documentElement.appendChild(script);