从 Firefox 附加组件(Webextension API)修改网页:如何正确访问元素?

Modifying a web page from Firefox add-on (Webextension API): how to access the elements properly?

我正在将旧的 Firefox 扩展迁移到 WebExtenstion API。这是我的扩展程序的作用:

  1. 向工具栏添加一个按钮
  2. 在选项中指定四个设置
  3. 当用户单击按钮时,我会验证 URL。如果 URL 匹配三个可能值之一,我将使用选项页面中的值填充页面上的一些输入元素,然后单击表单按钮。

这是我的 manifest.json:

{

  "manifest_version": 2,
  "name": "Login",
  "version": "3.0",

  "description": "Login to myinterfaces",
  "homepage_url": "localhost",
  "icons": {
    "48": "icons/button-1.png"
  },

  "permissions": [
    "activeTab", "storage", "tabs"
  ],

  "browser_action": {
    "default_icon": "icons/button-1.png",
    "default_title": "My Login"
  },


  "options_ui": {
    "page": "options.html"
  },


  "background": {
    "scripts": ["index.js"]
  }
}

在index.js中,我成功地从选项页面中获取了值并确定了我的活动选项卡的URL。之后,我试图修改页面上的值。这是我的做法:

var doc = window.content.document;

doc.getElementById("btnLogin").disabled = false;
doc.getElementById("loginUserName").value = loginUserName;
doc.getElementById("loginPassword").value = loginPassword;

但是对于...

doc.getElementById("btnLogin").disabled = false;

...我得到:

TypeError: doc.getElementById(...) is null

所以我读了这个页面:https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Modify_a_web_page

不确定我是否理解正确,所以这里有一些问题

是否可以通过后台脚本访问网页?如果可能的话,如何处理我遇到的错误?如果不可能,我是否理解应该在内容和后台脚本之间使用消息传递?那么我是否必须将 loginUserName 和 loginPassword 值从后台脚本发送到内容脚本并修改内容脚本中的页面?正确吗?

谢谢, 浣熊

Is it possible to access the web page from the background script?

没有。 window.content.document 是该上下文中的 背景页面 。将背景页面视为在不可见选项卡中打开的单独文档。

您需要一个内容脚本并需要与之通信。请参阅 Chrome 关于 extension architecture 的文档 - 我确定 MDN 上有类似的文档。

If it is not possible, do I understand right that I am supposed to use messaging between content and background scripts? So do I have to send loginUserName and loginPassword values from the background script to the content script and modify the page in the content script?

这是正确的,但如果您使用 browser.storage 作为选项,您可以直接从内容脚本访问它。

但是您需要消息传递:只有后台页面可以为您的工具栏按钮获取 onClicked 事件(WebExtension 术语中的 "browser action")。

请注意,您不必提前(通过清单)注入内容脚本。您可以在此处使用 programmatic injection + "activeTab" 权限,这会在不使用您的扩展程序时为用户带来更好的性能,并且远没有那么可怕的权限警告。