动态创建的iframe中的window.onerror在lne 0处给出脚本错误

时间:2012-09-06 12:34:04

标签: javascript iframe

我正在将iframe的源设置为html字符串,如下所示,让它执行我存储在内存中的html字符串。

window.sHTML = html;
iframe.src = 'javascript:parent.sHTML';

html字符串包含这样的javascript代码:

window.onerror = function(a,b,c) {
  console.log(a);
  console.log(b);
  console.log(c)
  return true;
}

当iframe发生错误时,它会记录“脚本错误”,“”,“0”,而不是给我实际的错误信息。

我了解当有问题的iframe是跨域时,可能会发生这种情况:Cryptic "Script Error." reported in Javascript in Chrome and Firefox

但是,iframe不是跨域的,它只是我动态创建的东西。是否有任何方法可以使window.onerror将其视为非跨域iframe,以便我可以从window.onerror访问正确的错误信息?

1 个答案:

答案 0 :(得分:0)

如果您需要使用HTML字符串动态填充iframe内容,document.write可能会有效:

var iframe = document.createElement('iframe');

document.body.appendChild(iframe);

iframe.contentDocument.open();
iframe.contentDocument.write(yourHTMLString);
iframe.contentDocument.close();

reference