复制事件中的event.clipboardData.setData

kof*_*fus 19 html javascript w3c dom-events clipboarddata

我看过很多帖子但是找不到以下两个问题的明确答案,因为看起来标准和浏览器支持一直在不断变化.

  1. 根据标准,使用event.clipboardData.setData在'copy'事件处理程序中更改剪贴板是合法的操作吗?

  2. 最新版本的Chrome/FF/Safari/IE/Chrome iOS/Android/iPhone是否支持此功能?

谢谢!

Nic*_*lay 40

截至2016年,剪贴板API确实在积极开发中,但这是我对当前事态的理解.

支持使用event.clipboardData.setData()

规范允许event.clipboardData.setData()'copy'事件处理程序内部更改剪贴板(只要事件不是合成的).

请注意,您需要阻止事件处理程序中的默认操作,以防止您的更改被浏览器覆盖:

document.addEventListener('copy', function(e){
  e.clipboardData.setData('text/plain', 'foo');
  e.preventDefault(); // default behaviour is to copy any selected text
});
Run Code Online (Sandbox Code Playgroud)

要触发复制事件,请使用execCommand

如果您需要触发复制事件(而不仅仅是处理用户通过浏览器UI发出的复制请求),则必须使用document.execCommand('copy').它只适用于某些处理程序,例如click处理程序:

document.getElementById("copyBtn").onclick = function() {
  document.execCommand('copy');
}
Run Code Online (Sandbox Code Playgroud)

浏览器支持各不相

https://github.com/garykac/clipboard/blob/master/clipboard.md有一个兼容性表execCommand('copy').

您可以使用下面的代码段对此进行测试,请对结果进行评论.

更多资源

测试用例

window.onload = function() {
  document.addEventListener('copy', function(e){
    console.log("copy handler");
    if (document.getElementById("enableHandler").checked) {
      e.clipboardData.setData('text/plain', 'Current time is ' + new Date());
      e.preventDefault(); // default behaviour is to copy any selected text
    }
    // This is just to simplify testing:
    setTimeout(function() {
      var tb = document.getElementById("target");
      tb.value = "";
      tb.focus();
    }, 0);
  });
  document.getElementById("execCopy").onclick = function() {
    document.execCommand('copy'); // only works in click handler or other user-triggered thread
  }
  document.getElementById("synthEvt").onclick = function() {
    var e = new ClipboardEvent("copy", {dataType: "text/plain", data:"bar"});
    document.dispatchEvent(e);
  }
}
Run Code Online (Sandbox Code Playgroud)
<html>
<input id="enableHandler" type="checkbox" checked>
<label for="enableHandler">Run clipboardData.setData('text/plain', ...) in the "copy" handler</label>
<p>Try selecting this text and triggering a copy using</p>
<ul>
    <li><button id="execCopy">document.execCommand('copy')</button> - should work.</li>
    <li><button id="synthEvt">document.dispatchEvent(clipboardEvent)</button> - should NOT work</li>
    <li>with keyboard shortcut - should work</li>
    <li>or from the context menu - should work</li>
</ul>
<p>If the "copy" handler was triggered, the focus will move to the textbox below automatically, so that you can try pasting from clipboard:</p>
<input type="text" id="target" size="80">
Run Code Online (Sandbox Code Playgroud)

Async Clipboard API将提供一种更简单的方法来管理剪贴板

实现后,execCommand(cut / copy / paste)将允许您编写如下代码:

navigator.clipboard.writeText('Text to be copied')
  .then(() => {
    console.log('Text copied to clipboard');
  })
  .catch(err => {
    // This can happen if the user denies clipboard permissions:
    console.error('Could not copy text: ', err);
  });
Run Code Online (Sandbox Code Playgroud)

Chrome 66开始发布部分实施,他们发布了一篇关于新API的文章.


Cha*_*ira 13

您也可以将其转换为调用自己的处理程序并将其删除的函数

function copyStringToClipboard (string) {
    function handler (event){
        event.clipboardData.setData('text/plain', string);
        event.preventDefault();
        document.removeEventListener('copy', handler, true);
    }

    document.addEventListener('copy', handler, true);
    document.execCommand('copy');
}
Run Code Online (Sandbox Code Playgroud)

  • 请注意,“event.clipboardData.setData”仅在由用户生成的“复制”/“粘贴”/类似事件触发时可靠地工作。因此,上面的“copyStringToClipboard”在一般情况下不起作用,因为调用“document.execCommand”生成的“copy”事件是合成的。 (2认同)