Search code examples
javascriptjsongoogle-chrome-extension

Google Chrome extension "Service worked registration failed" "Uncaught ReferenceError: document is not defined"


I'm designing a Google Chrome extension. My goal is to have an image inserted into the body of the website that the user is looking at. When I try it out, I get two errors: "Service worked registration failed" and "Uncaught ReferenceError: document is not defined".

I've tried using a try and catch system, a different JavaScript wrapper, adjusting the "permissions" & "host-permissions", adding "minimum_chrome_version", adding "web_accessible_resources", and more. Nothing has worked so far. Here's my code:

manifest.json:

{
  "name": "blah",
  "description": "blah",
  "version": "1.0",
  "manifest_version": 3,
  "icons": {
    "16": "icon.png",
    "32": "icon.png",
    "48": "icon.png",
    "128": "icon.png"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "minimum_chrome_version": "93",
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [{
       "matches": ["<all_urls>"],
       "js": ["background.js"],
       "css":["popup.css"]
    }],

  "permissions": [
    "storage", 
    "activeTab", 
    "scripting"
  ],
  "host_permissions": [
   "<all_urls>" 
  ],
  "web_accessible_resources": [
    {
      "resources": ["ezgif-3-9576363471.gif"],
      "matches": ["<all_urls>"]
    }
   ]
}

background.js:

const img = document.createElement("img");
img.src = chrome.runtime.getURL("ezgif-3-9576363471.gif");
document.body.append(img);

background-wrapper.js:

try {
  importScripts("background.js");
} catch (e) {
  console.error(e);
}

To summarize, I'm trying to figure out how to let document be defined, and how to properly use service-worker. Thanks in advance!


Solution

  • Answer given by @wOxxOm in the comment sections. Not sure how to mark as resolved without posting an answer.

    "Service worker doesn't have document so you can't use it there. You can do it in a content script or in the action popup."

    "Don't load service worker anywhere at all. The only place where it should be declared is manifest.json. You don't need a service worker for the popup, so in this case you can remove it everywhere. You need popup.js and load it in popup.html. Note that the popup is a separate window so it has its own separate devtools: right-click inside the popup and select "inspect" in the menu."