5

Am using the following function to put some text to my clipboard:

navigator.clipboard.writeText('Text to be copied').then(function() {
            console.log('Template copied to clipboard')
          }, function() {
            console.log('Unable to write to clipboard. :-(');
          });

Unfortunately, It doesn't work on Mozilla & IE. It works fine on Chrome. I've already tried using:

Document.execCommand('copy')

I found this tutorial in developers.google.com, but the example seems to work fine in Chrome and not in other browsers. What am I doing wrong here ?

deltaforce
  • 524
  • 1
  • 8
  • 25
  • 1
    Using a not widely supported feature? (It will come in FF63). – Kaiido Sep 05 '18 at 05:31
  • document.execCommand not Document.execCommand. IE has a security zone setting for clipboard access... make sure you are accepting the default IE security zone settings. (Internet Options>Security tab, click "Reset all zones to default". Are you developing/learning using a local html file? or are you using a html file that is on a server or your localhost? – Rob Parsons Sep 07 '18 at 02:19

2 Answers2

11

I'm not an expert on UI Web Development. I've faced a similar situation and I tried to use Document.execCommand('copy') as well. It didn't work for me either. So, I've made it work both on IE and Chrome like this. I hope this block of code can help you to sort this out.

$scope.CopyToClipBoard = function (text) {        
    if (navigator.clipboard != undefined) {//Chrome
        navigator.clipboard.writeText(text).then(function () {
            console.log('Async: Copying to clipboard was successful!');
        }, function (err) {
            console.error('Async: Could not copy text: ', err);
        });
    }
    else if(window.clipboardData) { // Internet Explorer
        window.clipboardData.setData("Text", text);
    }
};

I took the IE solution from here: How do I copy to the clipboard in JavaScript?

Sebastian Inones
  • 1,561
  • 1
  • 19
  • 32
0
var text = document.getElementById('copyText');
text.select();  
document.execCommand("copy");  
Jay Patel
  • 218
  • 2
  • 8
  • 3
    Please add further details to expand on your answer, such as working code or documentation citations. – Community Sep 01 '21 at 09:00