0

I'm trying to make an extension in Google Chrome that count the number of <li> elements on a website. The problem is that the script I made will not target the ActiveTab DOM but the extension DOM by default. How can I make it target the ActiveTab DOM and not the Extension DOM ?

This is my manifest.json:

"manifest_version": 2,

  "name": "My Extension",
  "description": "Still in test",
  "version": "1.0",

  "background": {
          "persistent": false,
          "scripts": ["background.js"]
      },

  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["scripts.js"]
    }
  ],

   "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

  "icons": { "16": "logo.png",
           "48": "logo.png",
          "128": "logo.png" },

  "browser_action": {
    "default_icon": "logo.png",
    "default_popup": "popup.html",
    "default_title": "Click to open menu"
  },
  "permissions": [
    "tabs",
    "activeTab",
    "https://ajax.googleapis.com/"
]

This is my button:

<input type="button" class="button-1" value="Count elements" id="counter">

This is my script in scripts.js:

document.addEventListener('DOMContentLoaded', function() {
    var link = document.getElementById('counter');
    link.addEventListener('click', function() {
   console.log(document.getElementById("mylist").getElementsByTagName("li").length);
    });
});

And this is the error that shows up because the wrong DOM is targetted:

Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
  • You can use a background page, get the active tab from there, then use chrome.tabs.executeScript to inject the script into that page. –  Aug 21 '17 at 13:52
  • Please [edit] the question to be on-topic: include a [mcve] that duplicates the problem. For Chrome extensions or Firefox WebExtensions this almost always means including your *manifest.json* and some of the background, content, and/or popup scripts/HTML. Questions seeking debugging help ("why isn't this code working the way I want?") must include: (1) the desired behavior, (2) a specific problem or error and (3) the shortest code necessary to reproduce it *in the question itself*. Please also see: [What topics can I ask about here?](//stackoverflow.com/help/on-topic), and [ask]. – Makyen Aug 22 '17 at 03:31

0 Answers0