在Firefox WebExtension中将文本从后台脚本复制到剪贴板 [英] Copy text to clipboard from background script in a Firefox WebExtension

查看:99
本文介绍了在Firefox WebExtension中将文本从后台脚本复制到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的Chrome扩展程序移植到Firefox。它有一个粘贴到剪贴板功能。但是,我还没有在Firefox中这样做的运气。这是我在后台脚本中要做的事情:
$ b

  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');
记录器(文本);
document.body.removeChild(input);

这在Chrome中正常运行。我的清单中有 clipboardWrite 权限。任何提示,为什么它不与Firefox工作?

解决方案

你正试图从后台脚本,这将不会工作。 MDN页面:与剪贴板交互 针对浏览器的注意事项 Firefox:


您可以在所有执行上下文中像这样写入剪贴板,除了背景页面之外。在Firefox中,您不能选择文本或在后台页面中关注输入字段,因此无法从后台页面写入剪贴板。


您需要在其他上下文中写入剪贴板。例如,您可以注入一个内容脚本,或者打开一个选项卡或窗口到您的扩展中的页面。你如何选择这样做将取决于你的扩展的额外权限(例如 tab ),当前打开的标签(是否有打开的标签你可以注入一个脚本),什么样的视觉效果是你可以接受的(例如,简单地打开一个你不激活的标签,这个标签对用户来说可能是或者可能不是)。

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?

解决方案

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).

这篇关于在Firefox WebExtension中将文本从后台脚本复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆