Chrome 扩展程序给出错误:未捕获的类型错误:无法读取 null

时间:2021-01-20 17:51:22

标签: javascript html dom google-chrome-extension browser-action

问题:我正在尝试创建一个简单的 Chrome 扩展程序来帮助我的工作,而且我的函数似乎在创建 DOM 之前尝试在 DOM 中查找该对象。

错误信息

Error Message given by Chrome Extension: 'Uncaught TypeError: Cannot read property addEventListener of null', 'Context
_generated_background_page.html
Stack Trace
contents.js:26 (anonymous function)'

我尝试过的:

  1. 将我的 content.js 函数包装在 window.onload = function () {}
  2. 将我的 content.js 函数包装在 document.addEventListener('DOMContentLoaded', function () {}
  3. 将我的 HTML <script></script> 标签移动到我的 popup.html 文档的底部。
  4. 使用 chrome.browserAction.onClicked 方法,虽然我可能没有正确使用它,因为我对它们很陌生。

代码库现在所处的位置

manifest.json 文件:

    {
  "short_name": "Shadow",
  "name": "Shadow Root Finder",
  "version": "1.0",
  "description": "highlights elements where shadowRoots are present",
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": ["contents.js"]
    }
  ],
  "permissions": [
    "storage",
    "activeTab",
    "declarativeContent"
  ],
  "icons": {
      "192": "/images/192_192_mission.png",
      "512": "/images/512_512_mission.png"
    },
  "background": {
    "scripts": [
      "background.js",
      "contents.js"
    ],
    "persistent": false
  },
  "browser_action" : {
    "default_popup" : "popup.html",
    "default_icon" : {
      "48": "/images/192_192_mission.png",
      "128": "/images/512_512_mission.png"
    }
  },
  "manifest_version": 2

}

popup.html 文件:

<html>
  <head>
    <style>
      button {
        height: 20px;
        width: 20px;
      }
    </style>
  </head>
  <body>
    <button id="searchTheShadowsButton"></button>
  </body>
</html>

background.js 文件:

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript({
    code: "/contents.js",
    allFrames: true
  });
});

content.js 文件:

document.addEventListener('DOMContentLoaded', function() {
//define variables
  let blue = '#5F9CE0';
  let peach = '#E07255';
  let red = '#AD395A';
  let count = 0;
  let nodeList = [];
  let windowDoc = document.getElementsByTagName('*');
  //define function
  function beginSearch () {
        console.log('search the Shadows activated: line 10')

          for (i = 0; i < windowDoc.length; i++) {
            console.log("entered for loop")
            if (windowDoc[i].shadowRoot) {
              console.log("entered if statement")
              count +=1;
              console.log('current count is: ' + count);
              windowDoc[i].parentNode.style.background = blue;
              nodeList.push(windowDoc[i].host.nodeName);
              console.log('nodes with shadowRoots include: ' + nodeList)
            }
          }
      };
  //set up listener
  document.getElementById('searchTheShadowsButton').addEventListener('click', beginSearch)
})

预期的用户界面:

  1. 客户点击浏览器中的图标
  2. 浏览器弹出窗口打开以显示按钮
  3. 用户点击按钮,然后触发 beginSearch() 函数
  4. 带有 shadowRoots 的元素以浅蓝色突出显示

0 个答案:

没有答案