在弹出窗口上设置onerror处理程序

时间:2014-11-07 23:46:50

标签: javascript error-handling popup

我想将回调传递给显示弹出窗口的函数(为方便起见,我在示例中将其设为iframe)。但是,从引用到新打开的窗口设置它时,我无法使window.onerror工作。我究竟做错了什么? (在Chrome中测试)

嵌入式脚本运行器不起作用,所以这里有一个小提琴http://jsfiddle.net/mendesjuan/PWSDF/35/

HTML

<button id="btn">New Window</button>
<button id="btn2">New Window 2</button>
<iframe name="popme"></iframe>

的JavaScript

// Works
document.getElementById('btn').addEventListener('click', function () {
    var win = window.open('', 'popme');
    var doc = win.document;
    doc.open();
    doc.write(
        "<html>" +
        "<head>" +
        "<scr" + "ipt>window.onerror = function() { alert(1); return true}</scr" + "ipt>" +
        "<scr" + "ipt>badCall1()</scr" + "ipt>" +
        "</head>" +
        "<body>Nothing really</body>" +
        "</html>"

    );
    doc.close();
});
// Doesn't work
document.getElementById('btn2').addEventListener('click', function () {
    var win = window.open('', 'popme');
    var doc = win.document;
    win.onerror = function () {
        alert(1);
        return true;
    }
    doc.open();
    doc.write(
        "<html>" +
        "<head>" +
        "<scr" + "ipt>badCall2()</scr" + "ipt>" +
        "</head>" +
        "<body>Nothing really 2</body>" +
        "</html>");
    doc.close()
});

1 个答案:

答案 0 :(得分:1)

在打开文档后附加 onerror 处理程序似乎有效。但是,我不确定为什么会这样。

JSBin(仅在Chrome中测试):http://jsbin.com/seveniqubi/1/edit?html,js,output

document.getElementById('btn2').addEventListener('click', function(e) {
  var win = window.open('', 'popme');
  var doc = win.document;

  doc.open();

  win.onerror = function(message, url, line) {
    alert(message);
    return true;
  };

  doc.write(
    "<html>"+"<head>" +
    "<scr" + "ipt>badCall2()</scr" + "ipt>" +"</head>" +
    "<body>Nothing really 2</body>" + "</html>");

  doc.close();                                                             
});