gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:29:00 26 4
gpt4 key购买 nike

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

嵌入式脚本运行器无法工作,所以这里有一个 fiddle 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()
});

最佳答案

打开文档后附加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();
});

关于javascript - 在弹出窗口上设置 onerror 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26811956/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com