javascript - 从 Firefox 插件(Webextension API)修改网页 : how to access the elements properly?

标签 javascript firefox dom firefox-addon firefox-addon-webextensions

我正在将旧的 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 是该上下文中的背景页面。将背景页面视为在不可见选项卡中打开的单独文档。

您需要一个内容脚本并需要与其进行通信。请参阅有关 extension architecture 的 Chrome 文档- 我确信 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 术语中的“浏览器操作”)。

请注意,您不必提前注入(inject)内容脚本(通过 list )。您可以使用programmatic injection + 此处的“activeTab”权限,这可以在用户不使用您的扩展时获得更好的性能,并且权限警告也不会那么可怕。

关于javascript - 从 Firefox 插件(Webextension API)修改网页 : how to access the elements properly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46098697/

相关文章:

javascript - 检测混合设备

javascript - 无法删除 Firefox 中的输入

javascript - Firefox 4 中的 HTML 5 支持

javascript - 根据子事件查找父元素

javascript - 如何使用 jQuery 显示具有特定类的第一个隐藏 div?

javascript - 如何删除字符串的一部分并保存到变量中?

javascript - 如何使用 jQuery 获取表中前两个 <tr> 的高度?

html - FireFox 中的 `contenteditable = true` 高度问题

javascript - 如果 id 匹配则删除标签但保留文本

javascript - 对 React 中的状态应用实时数学运算,引发输出/状态/dom 的变化