weird Uncaught TypeError: Cannot set property ‘onclick’ of null

When you declare background in manifest.json, it creates a background page where the specified scripts run. It’s a hidden separate page. You can debug it its own separate devtools.

The browser_action or page_action popup is also a separate page. It’s not related to the background script/page. It also has its own separate devtools which you can access by right-clicking inside the popup and choosing “Inspect”.

You can use both devtools to debug the problem: set breakpoints, reload the page via Ctrl-R or F5 key, step through the code and actually see what happens so there’s no need to guess.

Currently you run the same main.js in two pages. So, one instance of main.js runs in the background script’s page where DOM is empty and naturally it doesn’t find any elements.

The solution is to split it into two scripts. One script will be the background script that registers API stuff. Another script will run in the popup and deal with UI stuff.

  1. In manifest.json declare "background": {"scripts": ["bg.js", "persistent":false]}

  2. Make bg.js:

    chrome.runtime.onInstalled.addListener(() => {
      chrome.declarativeContent.onPageChanged.removeRules(() => {
        chrome.declarativeContent.onPageChanged.addRules([{
          conditions: [
            new chrome.declarativeContent.PageStateMatcher({
              pageUrl: {hostEquals: 'steamcommunity.com'},
            }),
          ],
          actions: [new chrome.declarativeContent.ShowPageAction()],
        }]);
      });
    });
    
  3. Make popup.js:

    document.getElementById('main-switch').onclick = function () {
      var elements = document.getElementsByTagName('span');
      console.log('Elements:', elements);
    };
    
  4. Load it in your html: <script src=popup.js></script>

    No need for defer or async attributes. No need for window.load either: the script already runs when DOM is ready as it’s the last thing in HTML.

Notes:

  • To view the console output, use the correct devtools as explained at the beginning of this answer.
  • To gray out the icon on non-matching sites, see this answer.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top