0

Im trying to develop a simple chrome extension that needs some functionality to get the current amount of like on a youtube video.

Here is my manifest.json

{
  "name": "xx",
  "version": "0.0.x",
  "manifest_version": 3,
  "description": "xx",
  "homepage_url": "xx",
  "default_locale": "en",
  "content_scripts": [
    {
      "matches": [
        "https://www.youtube.com/*"
      ],
      "js": [
        "src/inject/inject.js",
        "js/jquery/jquery.js"
      ]
    }
  ]
}

everything seems to be working as intended, and jquery and my inject.js script seem to be running fine, I can print stuff to the console and everything.

My problem comes when trying to select the text on the page that says the current amount of like on the video being played. When I open the chrome console, without having the extension enable or anything, I can type


> l = document.getElementsByClassName("style-scope ytd-toggle-button-renderer style-text")[1]

> likes = parseInt(l.getAttribute("aria-label").replace(/\D/g, ""));

and get the information that way.

This is my inject.js, its almost identical to my initial chrome console endeavor

l = document.getElementsByClassName("style-scope ytd-toggle-button-renderer style-text")[1]
likes = parseInt(l.getAttribute("aria-label").replace(/\D/g, ""));
        
console.log(likes)

when it's run through the extension by going to a youtube video, I get this error in the console

Uncaught TypeError: Cannot read properties of undefined (reading 'getAttribute')
    at inject.js:7

looks like the extension can't find the element, which is weird because it works in the chrome console. Any ideas?

piffle
  • 33
  • 6
  • 1
    Is the element you're trying to access created dynamically? – Barmar Dec 27 '21 at 06:42
  • I think so, it is a tag that shows the number of likes under the video – piffle Dec 27 '21 at 06:51
  • Your extension code is accessing the element when the page is first loaded, not waiting for JavaScript to create elements dynamically. You could use a MutationObserver to detect when the element is added. – Barmar Dec 27 '21 at 07:22
  • See [How to detect page navigation on YouTube and modify its appearance seamlessly?](https://stackoverflow.com/a/34100952) – wOxxOm Dec 27 '21 at 08:30

0 Answers0