firefox webextension alternative to addon clipboar

2019-07-28 11:49发布

问题:

I am trying to develop a Firefox extension which involves copying an image to the clipboard. In the past, it appears that this was accomplished using the clipboard addon sdk. However, this is being deprecated so I need to find another way to copy an image to the clipboard. The docs mentioned using document.execCommand('copy') but I cant get that to work for copying images.

From searching the web it seems that its normally not possible to copy an image to the clipboard in Javascript but I was wondering if Firefox has some sort of webextensions API to access the clipboard.

Edit: here is the code I have been using to try to copy images:

document.body.appendChild(img);
let range = document.createRange();
range.setStartBefore(img);
range.setEndAfter(img);
range.selectNode(img);
window.getSelection().addRange(range);
var successful = document.execCommand('copy');
window.getSelection().removeAllRanges();
document.body.removeChild(img);

img is an HTML image element. Nothing happens when it runs, though

回答1:

WebExtensions has setImageData().

Copy an image that was bundled with the extension:

// requires the API permission "clipboardWrite"

fetch(browser.runtime.getURL('image.png'))
.then(response => response.arrayBuffer())
.then(buffer => browser.clipboard.setImageData(buffer, 'png'));

clipboard.setImageData() - Mozilla | MDN