I am trying to access any element on YouTube from a content script.
manifest.json
"content_scripts": [
{
"run_at": "document_end",
"matches": ["*://www.youtube.com/watch?v=*"],
"js": ["content/content.js"]
}
]
However, when logging the element, I sometimes get null and sometimes the element is logged.
content.js
document.addEventListener('DOMContentLoaded', afterDOMLoaded)
function afterDOMLoaded() {
const element = document.getElementById('top')
console.log(element)
}
It works when using setTimeout
setTimeout(function(){
const element = document.getElementById('top')
console.log(element)
}, 3000)
I read here that this is because the element is being added later dynamically, by the page's javascript, and the only way to solve this is by using a MutationObserver/mutation-summary. This seems like a lot of hassle for just accessing an element. Isn't there any other way?