0

I'm creating an extension, and I want it to be able to find specific words on any website and highlight them. However, after I loaded my extension, I promptly got an error message. Does anyone know how to fix this?

My code is below.

background.js

chrome.runtime.onInstalled.addListener(() => {
  chrome.action.setBadgeText({
    text: "OFF",
  });
});

if (document !== undefined) {

const all = '*://*/*'
const screenwords = document.querySelectorAll('*');
var wlist = ["dog", "cats"];

chrome.action.onClicked.addListener(async (tab) => {
  if (tab.url.startsWith(all)) {
    // Retrieve the action badge to check if the extension is 'ON' or 'OFF'
    const prevState = await chrome.action.getBadgeText({ tabId: tab.id });
    // Next state will always be the opposite
    const nextState = prevState === 'ON' ? 'OFF' : 'ON';

    // Set the action badge to the next state
    await chrome.action.setBadgeText({
      tabId: tab.id,
      text: nextState,
    });

  if (nextState === "ON") {
    /*
    // search for words in list
    var foundwords;
    var wcounter;
    var position;
    for (var i = 0; i < screenwords.length; i++) {
      var results = screenwords.search(wlist[i]);
      if (results != -1) { // if words from list are found
        foundwords = true; // set foundwords to true
        wcounter++; // increment wcounter by +1
        position.i = results;
        }
    };
*/
    for (let i = 0; i < screenwords.length; i++) {
      for (let j = 0; j < wlist.length; j++) {
        if (screenwords[i].innerHTML.includes(wlist[j])) {
          screenwords[i].innerHTML = screenwords[i].innerHTML.replace(wlist[j], "***");
        };
    };
    }
  } else if (nextState === "OFF") {
    location.reload;
  };
}});


}

manifest.json

{
  "manifest_version": 3,
  "name": "TESTING 231",
  "description": "hello, world",
  "version": "1.0",
  "icons": {
    "16": "images/icon-16.png",
    "32": "images/icon-32.png",
    "48": "images/icon-48.png",
    "128": "images/icon-128.png"
  },
  "background": {
    "service_worker": "background.js"
  },
  "commands": {
    "_execute_action": {
      "suggested_key": {
        "default": "Ctrl+B",
        "mac": "Command+B"
      }
    }
  },
  "permissions": ["activeTab", "scripting"],
  "action": {
    "default_icon": {
      "16": "images/icon-16.png",
      "32": "images/icon-32.png",
      "48": "images/icon-48.png",
      "128": "images/icon-128.png"
    }
  }
}

I don't have a popup.html file, as the program is supposed to run as soon as the user clicks on the extension.

I've gone through the code, and there doesn't seem to be any typos. The error shows up at '''background.js''' if (document !== undefined). Thanks!

1 Answers1

0

You Cannot access DOM from Service Worker.

An extension service worker cannot access the DOM, though you can use it if needed with offscreen documents. Blockquote

Documentation: https://developer.chrome.com/docs/extensions/mv3/service_workers/

If you want to access the DOM of Extension, You should use Popup Script https://developer.chrome.com/docs/extensions/mv3/user_interface/#popup

OR, If you want to execute Javascript from the context of the webpage, You should use Content Script. https://developer.chrome.com/docs/extensions/mv3/content_scripts/

BadPiggie
  • 5,471
  • 1
  • 14
  • 28
  • Thanks for the documentation! If I'm understanding this correctly, there is no way for me to implement my code without adding an html document of some sort? I'd really like to just be able to click on the extension without anything popping up. – thelovelightliveventure Aug 11 '23 at 10:47
  • You can, But it depends on your requirement. **Service Workers** mainly runs in the background (A separate thread) which has no connection between your extension or the webpages directly. But **Content Script** is different, It will be injected into a webpage by browser, So all the javascript in that script will be executed in that webpage. Communication between Content, Extension, and Service Workers should be done by registering event listeners and emitting events / Chrome APIs. I recommend you take some time and study well. – BadPiggie Aug 11 '23 at 10:53