I have an iframe page with external content. I do not want endless loops in the external content to break my entire page. Is there any way around this.
I tried installing something where the parent postMessages child iframe so often, and if the child iframe does not respond for too long, the parent changes the iframes src, but this does not seem to work. The setTimeout parent functions are no longer executed after the start of the iframe loop. Look at my code here (note that it will cause your tab to crash, if you run it, open the console before execution to view the log):
<html> <head> </head> <body> <script type="text/javascript"> var scr = 'script'; var html = '<html><head><script>\n' + ' window.addEventListener("message", answer, false);' + ' function answer() { console.log("answered"); parent.postMessage(\'hi\', \'*\');}' + ' setTimeout("while(1){console.log(\'in loop\')};", 3000)' + "</" + scr + "></head><body>IFRAME</body</html>"; var lastAnswer = (new Date()).getTime(); var iframe = document.createElement('iframe'); queryChild(); window.addEventListener("message", receive, false); function receive() { lastAnswer = (new Date()).getTime(); console.log('got answer'); } function queryChild() { console.log('querying'); if((new Date()).getTime() - lastAnswer > 5000) { console.log('killing'); iframe.src = ''; } else if(iframe.contentWindow){ iframe.contentWindow.postMessage('hi', '*'); } setTimeout(queryChild, 2000); }; document.body.appendChild(iframe); iframe.contentWindow.document.open(); iframe.contentWindow.document.write(html); iframe.contentWindow.document.close(); </script> </body> </html>
Any suggestions for resolving this issue?
source share