javascript - Chrome & IE : onpaste event not firing?

标签 javascript internet-explorer google-chrome paste

我(和许多其他人一样)正在尝试清理粘贴到 contentEditable iframe 中的文本。我没有使用 jQuery(它是一个非常古老的代码库)并且处理程序是这样附加的:

if (isIE) {
  iframe.attachEvent("onpaste",handler);
}
else {
  iframe.addEventListener("paste",handler,true);
}

这在 Firefox 和 Opera 中有效,但在 IE 10 和最新版本的 Chrome (29.0.1547.62) 中,处理程序永远不会被调用;我在处理程序的第一行放置了一个断点,但是当我粘贴一些文本时它没有到达断点并且粘贴的文本只是出现(未清理)。我尝试在 IE 9 模式下使用 IE10,但没有任何区别。其他处理程序似乎按预期被调用。

有人知道这里会发生什么吗?

TIA...

最佳答案

事实证明,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>

关于javascript - Chrome & IE : onpaste event not firing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18578916/

相关文章:

javascript - Angular2 Cli 项目中的 PouchDB 身份验证库

javascript - 以编程方式创建 SAPUI5 应用程序?

internet-explorer - 投影在 ie8 中不起作用并破坏其他浏览器上的样式

html - 网站在 Firefox 中运行良好,但在 Chrome 中运行不正常

android - 如何在 Android chrome 中禁用 ul li 链接缩放

css - 如何覆盖设备像素比

javascript - Firefox/Firebug 不显示抛出的错误消息

internet-explorer - 为什么单击 excel 中的超链接会在用户代理中使用 MSIE 7.0 生成 HTTP 请求?

javascript - 为什么 navigator.geolocation.getCurrentPosition 在 IE 11 上不起作用

javascript - 将变量从 PHP 传递到 AJAX 成功函数