Hi it's my first time using JavaScript and HTML so I might be doing something wrong:
I am trying to insert something new into a webpage using chrome extension, and my code sometimes work but sometimes not. For example, when I try to insert a text into any YouTube page, my code can querySelect id="logo" but not id="secondary". I don't have a good sense of JavaScript nor HTML, and I am completely stuck here.
Here is my manifest.json and my content.js:
{
"manifest_version": 3,
"name": "tutorial",
"version": "1.0",
"description": "Add text to YouTube page",
"content_scripts": [
{
"js": ["content.js"],
"matches": [
"https://www.youtube.com/*"
]
}
]
}
if(document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded',afterDOMLoaded);
} else {
console.log('DOM fully loaded and parsed');
const object = document.querySelector('#secondary');
if (object) {
const newElement = document.createElement('div');
newElement.innerText = 'Hello from the YouTube Element Injector!';
object.insertAdjacentElement('afterbegin', newElement);
} else {
console.log('object is null');
}
}
I would appreciate any advice! Thanks