事实证明,iframe 加载了一个空白页面,然后以编程方式填充了内容。在重写 iframe 文档之前添加了事件侦听器,这就是问题的原因。需要在重写 iframe 内容后添加侦听器。这是一个测试用例:
<html>
<head>
<title>Paste test&</title>
<script>
function handler() {
alert("Paste");
}
function register(iframe) {
//
// IE10 requires addEventListener to be used, so this
// is preferable to doing browser detection...
//
if (window.addEventListener) {
iframe.addEventListener("paste",handler,true);
}
else {
iframe.attachEvent("onpaste",handler);
}
}
function test() {
var iframe = document.getElementById("frm").contentWindow;
try {
var doc = iframe.document;
if (!doc) {
setTimeout(test,50);
return;
}
// register(iframe); // this won't work!
doc.open();
doc.write("<html><body>Paste text here: []</body></html>");
doc.close();
doc.body.contentEditable = true;
register(iframe); // this works!
}
catch (e) {
setTimeout(test,50);
return;
}
}
</script>
</head>
<body onLoad="test()">
Here is the iframe:
<p>
<iframe id="frm" src="blank.html" width="400" height="200"></iframe>
</body>