One possible way to achieve this is by using the navigator.clipboard.write
API, but keep in mind that this API is not available to background pages of Chrome extensions. A method I attempted involved creating a blob like this:
let blobFinal = null; // will store the blob object
const img = document.createElement('img');
// insert image data
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAsCAYAAAANUxr1AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAfJSURBVFhH7ZhLbFTXHcZ/9955j+dhjz1+Y/MqUEckgFwaQC0EuXmoUdNIjUiiSo2qZtFFd1GzaZR02U0X3VRZt1K6SKUWVVGloLJAFiFxEAGBwTZg/Lbn/bpzZ+6j/zsel6QteIwEYsE3ur7nPs453/nO/3WtjLz6rsNjBLV5fmzwhNBmeEJoMzwhtBm05L5j7zfbW8LR/dt5762XeOHZETRV4Vu...
document.body.appendChild(img);
setTimeout(() => {
// create canvas of similar size
const canvas = document.createElement('canvas');
canvas.width = img.clientWidth;
canvas.height = img.clientHeight;
const context = canvas.getContext('2d');
// copy image onto it
context.drawImage(img, 0, 0);
// we can apply transformations here if needed
// convert canvas data into a blob (asynchronous)
canvas.toBlob(function(blob) {
blobFinal = blob;
console.log('blob', blob);
document.body.removeChild(img);
}, 'image/png');
}, 1000);
Next step involves attaching this blob to clipboard during a 'copy' event:
editor.addEventListener('copy', (evt) => {
// preserve text data
evt.clipboardData.setData('text/plain', evt.clipboardData.getData('text/plain'));
evt.clipboardData.setData('text/html', evt.clipboardData.getData('text/html'));
// add binary data
evt.clipboardData.setData('image/png', blobFinal);
evt.preventDefault();
});
However, upon pasting this data, no files show up in the clipboard:
editor.addEventListener('paste', (evt) => {
console.log(evt.clipboardData.files.length); // prints 0
for (const file of evt.clipboardData.files) {
console.log('Size of file', file.size);
}
});
Even if there was one file, its 'size' property would still be zero. Surprisingly, information regarding this issue seems scarce. Therefore, my question remains: how can files be attached to the clipboard within a Chrome extension?