0

It's my first time trying to learn Firefox extension development. To get started, I'm trying to make a simple extension that alters some parts of the youtube.com homepage.

This is the manifest.json:

{
   "manifest_version": 2,
   "name": "Better Youtube jk idk what I'm doing",
   "version": "1.0",

   "description": "Yep yep yippie",

   "content_scripts": [
       {
           "matches": ["*://*.youtube.com/*"],
           "js": ["better_youtube.js"]
       }
   ]
}

and this is the better_youtube.js file:

document.getElementsByClassName("title style-scope ytd-guide-entry-renderer")[0].textContent = "something";

So, the element that this gets is the "home" link on the left side menu of the page. The reason I'm writing this post is that I'm getting an unusual behaviour:

  • If I load the youtube.com page with the extension already enabled, nothing happens and the link's text does not change
  • If, with youtube.com already loaded, I reload the script from the about:debugging page, it works

I tried running the change after 10 seconds (by passing the code to a setTimeout(changeLabel, 10000) call), but it kept showing this weird behaviour.

If it's of any use, I'm running Firefox 99.0.1

Thanks for any help.

Edit: I changed the code to

setTimeout(delayedUpdate, 10000);

function delayedUpdate(event)
{
    document.getElementsByClassName("title style-scope ytd-guide-entry-renderer")[0].innerHTML = "something";
}

and it now works, but I have to wait 10 seconds every time for it to load and it feels slow. Through console logging I noticed that Firefox "thinks" the page is loaded when I still see parts of it missing, the issue might stem from that, but I don't know how to address it. Maybe my extension is conflicting with some script running on the youtube page?

Alessandro Di Cicco
  • 147
  • 1
  • 2
  • 10
  • 1
    See [How to detect page navigation on YouTube and modify its appearance seamlessly?](https://stackoverflow.com/a/34100952) – wOxxOm Apr 19 '22 at 18:50
  • Thanks, that fixed most of the issues I had, the extension gets notified every time I navigate to a different section of the website (e.g.: home, shorts, trending...) but it doesn't work on the first time, since the `yt-navigate-finish` event is raised fires some ~500ms before the navigation bar appears. Is there a way that doesn't involve repeatedly comparing the HTMLElement against `undefined` to detect the first time it properly loads? – Alessandro Di Cicco Apr 19 '22 at 19:31
  • 1
    You can use MutationObserver. – wOxxOm Apr 19 '22 at 20:32

1 Answers1

0

Thanks to @wOxxOm, I found the solution: I can listen to some YouTube-specific events on document and I can use MutationObserver for when content on a page updates.

More info here.

Alessandro Di Cicco
  • 147
  • 1
  • 2
  • 10