javascript - 使用 Chrome 扩展时从弹出窗口获取网页的 document.body

标签 javascript google-chrome-extension firefox-addon google-chrome-devtools

我有一个基本的 Chrome 扩展程序,需要通过弹出窗口访问网页的 document.body

目前,当我尝试打开弹出窗口和控制台日志 document.body 时,它会记录弹出窗口的 document.body,而我想要网站的 document.body .

我该怎么做?

manifest.json

{
  "description": "Demo ext",
  "manifest_version": 2,
  "name": "Demo ext",
  "version": "1.0",
  "icons": {
    "48": "icons/icon-48.png"
  },
  "permissions": ["activeTab"],
  "browser_action": {
    "default_icon": "icons/icon-32.png",
    "theme_icons": [
      {
        "light": "icons/icon-32-light.png",
        "dark": "icons/icon-32.png",
        "size": 32
      }
    ],
    "default_title": "Demo ext",
    "default_popup": "popup/index.html"
  }
}

弹出/index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Demo ext</title>
  </head>
  <body>
    <h1>Title should be the websites which we are on 👇</h1>
    <script src="./app.js"></script>
  </body>
</html>

弹出/app.js

function main() {
  console.log(document.body)
  var title = document.createElement('div')
  title.innerHTML = document.title
  document.body.appendChild(title)
}

main()

我希望此处记录的document.body是网站的。我该怎么做?

最佳答案

我建议您查看此Chrome Extension Content Scripts

If your extension needs to interact with web pages, then it needs a content script. A content script is some JavaScript that executes in the context of a page that's been loaded into the browser. Think of a content script as part of that loaded page, not as part of the extension it was packaged with (its parent extension).

内容脚本可以通过与扩展程序交换消息来访问其父扩展程序使用的 Chrome API。他们还可以使用 chrome.runtime.getURL() 访问扩展文件的 URL,并像其他 URL 一样使用结果。

关于javascript - 使用 Chrome 扩展时从弹出窗口获取网页的 document.body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56515568/

相关文章:

javascript - 使用固定的左 div 水平滚动

javascript - jQuery - 与 Firefox 的兼容性问题

javascript - Chrome 扩展脚本内的函数返回错误的值

firefox-addon - 如何检索 XUL 元素的实际宽度和高度?

javascript - 使用内容脚本中的 `simple-prefs` 打开插件的选项页面

javascript - Sharepoint - 运行 Sp.Web.currentUser 属性

javascript - 寻找浏览器的边界

css - Chrome 扩展——防止 CSS 被改写

javascript - 如何在新打开的 chrome 选项卡上执行我的内容脚本?

javascript - 如何设置一个设置,使用户可以选择他们希望在 JavaScript 中显示的警报类型