0

I want to change youtube comments containing a certain keyword to something else, but to do that, I have to detect their text. I'm using a chrome extension with a manifest as follows:

{
  "manifest_version": 2,
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab",
    "https://ajax.googleapis.com/"
  ],
  "content_scripts": [{
    "css": ["styles.css"],
    "js": ["content.js"],
    "matches": ["https://*/*"],
    "run_at": "document_end"
  }]
}

and my content.js file is this:

alert("Starting");

Yet my alert goes off before the Youtube Comments or Messenger messages are loaded. How can I wait?

Jonathan Allen Grant
  • 3,408
  • 6
  • 30
  • 53
  • See also [Is there a JavaScript/jQuery DOM change listener?](//stackoverflow.com/a/39508954) and [How to detect page navigation on Youtube and modify HTML before page is rendered?](http://stackoverflow.com/questions/34077641/how-to-detect-page-navigation-on-youtube-and-modify-html-before-page-is-rendered) – wOxxOm Oct 01 '16 at 09:53

1 Answers1

2

YouTube comments and messenger messages are loaded Asynchronously, and your content.js runs at document_end i.e before these calls are preformed.

In the case of "document_end", the files are injected immediately after the DOM is complete, but before subresources like images and frames have loaded.

from https://developer.chrome.com/extensions/content_scripts

you'll have to use some sort of listener, probably a MutationObserver, in YouTube this code should work:

// select the target node
var target = document.getElementById('watch-discussion');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
       console.log(mutation.type);
    });    
});

// configuration of the observer:
var config = { childList: true };

// pass in the target node, as well as the observer options
 observer.observe(target, config);

based on https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

by listening to childList mutations of the comments wrapper you'll be able to fire code every time comments are loaded Asynchronously into the page

Jameson the dog
  • 1,796
  • 1
  • 11
  • 12