Search code examples
javascriptjqueryimagebase64clipboarddata

Javascript Clipboard SetData Error in Mozilla


I want to copy image programmatically. I have used executeCommand('copy')which was not working so I override copy listener by document.addEventListener('copy', modifyCopy); In modifyCopy function I convert base64 encoded string to blob url and set it into clipBoard by e.clipboardData.setData('image/png',blobUrl); In chrome it does not work but in Mozilla which after setting data when I go to paint it enable paint paste but gives following error.

you can check fiddle for what I have tried. http://jsfiddle.net/32mbd1o0/16/

enter image description here

function b64toBlob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;

var byteCharacters = atob(b64Data);
var byteArrays = [];

for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
  var slice = byteCharacters.slice(offset, offset + sliceSize);

  var byteNumbers = new Array(slice.length);
  for (var i = 0; i < slice.length; i++) {
    byteNumbers[i] = slice.charCodeAt(i);
 }

 var byteArray = new Uint8Array(byteNumbers);

  byteArrays.push(byteArray);
}

var blob = new Blob(byteArrays, {type: contentType});
 return blob;
}

const modifyCopy = e => {
                var contentType = 'image/png';
                var b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
                var blob = b64toBlob(b64Data, contentType);
                var blobUrl = URL.createObjectURL(blob);
alert(blobUrl);
                e.clipboardData.setData('image/png',blobUrl);
                e.preventDefault();
            };

document.addEventListener('copy', modifyCopy);

 $(".copyable").click(function (e) {
                $(this).attr("contenteditable", true);
                document.execCommand('copy');
            });

Solution

  • Firefox only supports these data types during copy and cut events Source.

    • text/plain
    • text/uri-list
    • text/csv
    • text/html
    • image/svg+xml
    • application/xml, text/xml
    • application/json

    One possible workaround described here, copies the image to the clipboard as html data. This works, but only if you want to paste on programs such as Microsoft Windows Word or other word processors. Programs for working with graphics (paint, photoshop, etc) do not understand what is on the clipboard.

    Finally, you can also create an extension for firefox that relies on the API clipboard.setImageData(). The clipboard.setImageData allows you to populate the clipboard with image data. This API is compatible with the Chrome apps API (it was added in Firefox 57) and it should still be considered experimental. This API requires the clipboardWrite permission.