Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clipboard.writeText() does'nt work on Mozilla & IE

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 ?

like image 882
deltaforce Avatar asked Jan 28 '23 12:01

deltaforce


2 Answers

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?

like image 189
Sebastian Inones Avatar answered Jan 31 '23 23:01

Sebastian Inones


var text = document.getElementById('copyText');
text.select();  
document.execCommand("copy");  
like image 35
Jay Patel Avatar answered Feb 01 '23 00:02

Jay Patel