Search code examples
javascriptgoogle-chrome-extensionfirefox-addongoogle-chrome-devtools

Get document.body of webpage from popup while using Chrome extension


I have a basic Chrome extension which needs to access document.body of the webpage through popup.

Currently, when I try to open popup & console log document.body, it logs the popup's document.body while I want the website's document.body.

How do I do that?

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"
  }
}

popup/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>

popup/app.js

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

main()

I want the document.body logged here to be of the website. How should I do it?


Solution

  • Indeed Content scripts were the way to go. I tried it but it didn't work for me but this answer solved it all.

    Just linking it since it explains everything better than I can :)