如何将文本复制到剪贴板(多浏览器)?

相关:Trello如何访问用户的剪贴板?


当前回答

我不愿意就此再加一个答案,但我想帮助像我这样的菜鸟,因为这是谷歌排名第一的结果。

在2022年,要将文本复制到剪贴板,您需要使用一行。

navigator.clipboard.writeText(textToCopy);

这将返回一个Promise,如果它复制,则该Promise将被解析,如果失败,则该Promise将被拒绝。

完整的工作功能如下:

async function copyTextToClipboard(textToCopy) {
    try {
        await navigator.clipboard.writeText(textToCopy);
        console.log('copied to clipboard')
    } catch (error) {
        console.log('failed to copy to clipboard. error=' + error);
    }
}

警告!如果您在测试时打开了Chrome开发工具,它将失败,因为浏览器要启用剪贴板,需要将窗口聚焦。这是为了防止随意网站更改剪贴板(如果你不想的话)。开发工具窃取了这一焦点,所以关闭开发工具,你的测试就会成功。

如果您想将其他内容(图像等)复制到剪贴板,请查看这些文档。

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API

这在浏览器中得到了很好的支持,您可以使用它。如果您担心Firefox,请使用权限查询来显示或隐藏按钮(如果浏览器支持)。https://developer.mozilla.org/en-US/docs/Web/API/Permissions/query

其他回答

其他方法将纯文本复制到剪贴板。要复制HTML(即,可以将结果粘贴到所见即所得编辑器中),只能在Internet Explorer中执行以下操作。这与其他方法有根本不同,因为浏览器实际上可以直观地选择内容。

// Create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
    contentEditable = true;
}
editableDiv.appendChild(someContentElement);

// Select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();
r.execCommand("Copy");

// Deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();

我把我认为最好的东西放在一起了。

使用cssText避免Internet Explorer中的异常,而不是直接使用样式。如果有选择,则恢复选择设置为只读,以便移动设备上不会出现键盘有一个适用于iOS的解决方案,因此它实际上可以像通常阻止execCommand一样工作。

这里是:

const copyToClipboard = (function initClipboardText() {
  const textarea = document.createElement('textarea');

  // Move it off-screen.
  textarea.style.cssText = 'position: absolute; left: -99999em';

  // Set to readonly to prevent mobile devices opening a keyboard when
  // text is .select()'ed.
  textarea.setAttribute('readonly', true);

  document.body.appendChild(textarea);

  return function setClipboardText(text) {
    textarea.value = text;

    // Check if there is any content selected previously.
    const selected = document.getSelection().rangeCount > 0 ?
      document.getSelection().getRangeAt(0) : false;

    // iOS Safari blocks programmatic execCommand copying normally, without this hack.
    // https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
    if (navigator.userAgent.match(/ipad|ipod|iphone/i)) {
      const editable = textarea.contentEditable;
      textarea.contentEditable = true;
      const range = document.createRange();
      range.selectNodeContents(textarea);
      const sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
      textarea.setSelectionRange(0, 999999);
      textarea.contentEditable = editable;
    }
    else {
      textarea.select();
    }

    try {
      const result = document.execCommand('copy');

      // Restore previous selection.
      if (selected) {
        document.getSelection().removeAllRanges();
        document.getSelection().addRange(selected);
      }

      return result;
    }
    catch (err) {
      console.error(err);
      return false;
    }
  };
})();

用法:复制到剪贴板(“部分文本”)

我的错。这仅适用于Internet Explorer。

这里还有另一种复制文本的方法:

<p>
    <a onclick="window.clipboardData.setData('text', document.getElementById('Test').innerText);">Copy</a>
</p>

我非常成功地使用了这个(没有jQuery或任何其他框架)。

function copyToClp(txt){
    var m = document;
    txt = m.createTextNode(txt);
    var w = window;
    var b = m.body;
    b.appendChild(txt);
    if (b.createTextRange) {
        var d = b.createTextRange();
        d.moveToElementText(txt);
        d.select();
        m.execCommand('copy');
    } 
    else {
        var d = m.createRange();
        var g = w.getSelection;
        d.selectNodeContents(txt);
        g().removeAllRanges();
        g().addRange(d);
        m.execCommand('copy');
        g().removeAllRanges();
    }
    txt.remove();
}

警告

制表符转换为空格(至少在Chrome中)。

ZeroClipboard是我找到的最好的跨浏览器解决方案:

<div id="copy" data-clipboard-text="Copy Me!">Click to copy</div>
<script src="ZeroClipboard.js"></script>
<script>
  var clip = new ZeroClipboard( document.getElementById('copy') );
</script>

如果您需要iOS的非Flash支持,只需添加一个回退:

clip.on( 'noflash', function ( client, args ) {
    $("#copy").click(function(){
        var txt = $(this).attr('data-clipboard-text');
        prompt ("Copy link, then click OK.", txt);
    });
});

http://zeroclipboard.org/

https://github.com/zeroclipboard/ZeroClipboard