如何使用javaScript将一些文本放入剪贴板?

时间:2018-09-03 11:28:28

标签: javascript jquery google-chrome mozilla

我想让用户将某些内容复制到剪贴板。我尝试了以下方法。

var textArea = document.createElement('textarea');
textArea.textContent = response['file_content'];
document.body.appendChild(textArea);

 var selection = document.getSelection();
 var range = document .createRange();
 range.selectNode(textArea)
 selection.removeAllRanges();
 selection.addRange(range);

 if(document.execCommand('copy'))
 {
     console.log('Template copied to clipboard');
 }else {
     console.log('Copying Failed');
 }

 selection.removeAllRanges();
 document.body.removeChild(textArea)

但不幸的是

document.execCommand('copy')

在Chrome 68和Mozilla Firefox 60中总是返回false。在IE 11中它似乎可以正常工作。我已经在SO上遇到了很多类似的问题,但是这些对我都不起作用。我不想使用闪光灯。

1 个答案:

答案 0 :(得分:7)

我在项目中使用了以下代码。.它对我有用。.

  

元素

<a rel="tooltip" data-placement="top" title="Copy code" class="copytext-btn copyText" href="javascript:void(0);"><i class="code-file-icn"></i></a>
  

ClickEvent:

jQuery(".copyText").click(function(e)
{
    e.preventDefault();
    copyTextToClipboard(jQuery('.GeneratedText').text());
});
  

功能:

function copyTextToClipboard(text) 
{
    var textArea = document.createElement("textarea");
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        var successful = document.execCommand('copy');
        if(successful)
        {
            // SuccessCode

        }
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copying text command was ' + msg);
    } 
    catch (err) 
    {
        console.log('Oops, unable to copy');
    }
}