Inject js code into iframe/send data between parent and iframe
by Amir Sharifian
HTML
<button id="toggle">
Stop/Start
</button>
<br />
<iframe id="myiframe" width="200" height="200" srcdoc="<div id='list'></div>"></iframe>
JavaScript
window.loop = true;
document.getElementById("toggle").addEventListener('click', function() {
window.loop = !window.loop;
console.log("loop status", window.loop)
});
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() {
let i = 0;
setInterval(function() {
console.log("iframe", parent.loop);
var p = document.createElement("span");
if (parent.loop) {
i++;
p.innerHTML = i;
} else {
p.innerHTML = 0;
}
document.getElementById('list').appendChild(p);
}, 2000)
}
`);
iframeDoc.documentElement.appendChild(script);