0

I was building a chrome extension that modifies the content on a Youtube video page.

The following is my code:

manifest.json

{
"name": "Chrome Demo",
"description": "Some Cool Description",
"version": "1.0",
"manifest_version": 3,
"content_scripts": [
    {
      "matches": ["https://www.youtube.com/watch*"],
      "js": ["temp.js"],
      "run_at": "document_end"
    }
]
}

temp.js

let observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
  if (!mutation.addedNodes) return;

  for (let i = 0; i < mutation.addedNodes.length; i++) {
    // do things to your newly added nodes here
    let node = mutation.addedNodes[i];
    
    if (node.id === 'contenteditable-root') {
        console.log(node);
        node.ariaLabel = 'XXX';
    }

    if (node.id === 'sections' && node.className === 'style-scope ytd-comments') {
        console.log(node);
        var para = document.createElement("P");               
        para.innerHTML = "This is a paragraph."; 
        node.childNodes[1].appendChild(para);
        console.log(node);
    }
  }
})
})

observer.observe(document.body, {
      childList: true
    , subtree: true
    , attributes: false
    , characterData: false
  })

My problem is: the para element I appended (in temp.js) disappears after showing up for a moment. And when I used the inspect tool to find the para element, it was not there. Can anyone help me with that? Thanks a lot!!

Frank
  • 11
  • You need to add it again if it's not present. You can replace your entire mutations.forEach with a simple check like `if (!document.querySelector('#my-cool-node'))` and see also [this answer](https://stackoverflow.com/a/34100952). – wOxxOm Jun 28 '21 at 19:32
  • Thank you so much for answering! I tried to add it repeatedly until it is added and it worked :) I am wondering if you know why this happens? Is it related to how Youtube loads pages? – Frank Jun 28 '21 at 22:28

0 Answers0