问题
I am porting my Chrome extension over to Firefox. It has a paste to clipboard function. But, I have not yet had any luck with doing that in Firefox. Here is what I am trying to do in my background script:
const input = document.createElement('textarea');
input.style.position = 'fixed';
input.style.opacity = 0;
input.value = text;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
logger(text);
document.body.removeChild(input);
This works fine in Chrome. I have the clipboardWrite
permission in my manifest. Any hints why it is not working with Firefox?
回答1:
You are trying to do this from a background script, which won't work. The MDN page: "Interact with the clipboard" in "Browser-specific considerations" says, for Firefox:
You can write to the clipboard like this in all execution contexts except background pages. In Firefox you can't select text or focus an input field in background pages, so you can't write to the clipboard from a background page.
You will need to be in some other context to write to the clipboard. For instance, you could inject a content script, or open a tab or window to a page in your extension. How you choose to do so will depend on the additional permissions you already have for your extension (e.g. tabs
), the tabs that are currently open (are there any tabs open in which you can inject a script) and what visual impact is acceptable to you (e.g. briefly opening a tab which you don't activate, which may, or may not, be perceptible to the user).
来源:https://stackoverflow.com/questions/45622608/copy-text-to-clipboard-from-background-script-in-a-firefox-webextension