我有一个包含外部内容的 iframe 页面。我不希望外部内容中的无限循环使我的整个页面崩溃。有什么办法可以解决这个问题。
我试图设置一些东西,父子 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>
关于如何解决这个问题的任何建议?