Javascript:父级可以杀死子iframe,如果它被卡在无限循环中?

asu*_*and 6 javascript iframe infinite-loop

我有一个页面,其中包含带有外部内容的iframe.我不希望外部内容中的无限循环崩溃我的整个页面.有没有办法解决这个问题.

我试图在父级postMessages子iframe的情况下设置一些内容,如果子iframe没有响应太长时间,则父级更改iframes src,但这似乎不起作用.一旦iframe开始循环,父级的setTimeout函数就不再执行了.在这里查看我的代码(请注意,如果执行它会使选项卡崩溃,在执行之前打开控制台以查看日志记录):

<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>
Run Code Online (Sandbox Code Playgroud)

有关如何解决这个问题的任何建议?

arv*_*ahl 5

My experience with this kind of problem is that unless you can access the external code before feeding it to the iframe (either as an URL or via the srcdoc attribute), the loop will completely interrupt any JavaScript execution.

无论您实现哪种超时功能,由于iframe代码执行都会消耗100%的资源,直到浏览器报告崩溃,它才会被调用。

您的选择是:

  • 在将代码添加到中之前,先自动对代码进行清理iframe,这是不切实际的,因为有无限种方法可以无限循环,并且您将无法全部捕获它们。您将必须编写一个扫描程序脚本,该脚本可以检测到无限循环,同时又不会在扫描代码的过程中崩溃。
  • 使用Google Caja之沙盒解决方案来清理代码。但是,如果不进行大量配置,这将在结构上更改代码。
  • In case of an application that has capabilites of creating virtual environments and monitoring them, you could execute the iframe code (let's say on a virtual machine of sorts), check if the process locks up and use that outcome to determine if you can safely set the iframe.src property to your code's URL. This might be the only solution that can guarantee some sort of guarantee that this code will not lock up immediately (however, there are many ways to have race conditions at some later point of execution, so there will not be a sure way to say it will never lock up the browser).

Summary: Unless you can find a way to test the code extensively before showing it in the iframe, you can not guarantee that the iframe code will not lock up the browser tab.