Search code examples
javascriptjquerygoogle-chromemozilla

How to put some text to clipboard using javaScript?


I want to enable user to copy some content to the clipboard. I tried the following.

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)

But unfortunately

document.execCommand('copy')

is always returning false in Chrome 68 and Mozilla Firefox 60. It seem to work fine in IE 11. I've already gone through a lot of similar questions on SO, But that all doesn't work for me. I don't want to make use flash.


Solution

  • I have used below code in my project.. Its working for me..

    Element

    <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:

    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');
        }
    }