I am currently learning how to develop chrome extensions. My goal is to create a basic extension that logs the title of the current YouTube video in the console.
This snippet represents the HTML structure for the YouTube Title:
<div id="title" class="style-scope ytd-watch-metadata">
<ytd-badge-supported-renderer class="style-scope ytd-watch-metadata" disable-upgrade="" hidden="">
</ytd-badge-supported-renderer>
<h1 class="style-scope ytd-watch-metadata">
<yt-formatted-string force-default-style="" class="style-scope ytd-watch-metadata">Elon’s "based" Grok AI has entered the chat…</yt-formatted-string>
</h1>
<ytd-badge-supported-renderer class="style-scope ytd-watch-metadata" disable-upgrade="" hidden="">
</ytd-badge-supported-renderer>
</div>
Below is the code I have written to retrieve the title, located within the ContentScript:
(()=>{
console.log(document.getElementById("title"));
console.log(document.querySelector("#title > h1 > yt-formatted-string"));
})();
The first line outputs
<div id="title" class="style-scope ytd-watch-metadata">
But the second line returns
null
When I try this in the Chrome console, the second line performs as expected. It's not working properly when executed using JavaScript.
Here is my manifest.json file:
{
"manifest_version": 3,
"name": "FillModule",
"description": "Fill test 001",
"version": "1.0.0",
"permissions": ["storage", "tabs"],
"author":"Aniket Vishwakarma",
"action": {
"default_icon": "assets/doggy.png",
"default_title": "Fill",
"default_popup": "popup/popup.html"
},
"background" : {
"service_worker": "background/background.js"
},
"content_scripts": [
{
"matches": ["https://*.youtube.com/*"],
"js": ["content/content.js"]
}
]
}
MY ATTEMPTS
I tried wrapping it in a "DOMContentLoaded" event listener like so:
document.addEventListener("DOMContentLoaded", () => {
console.log(document.querySelector("#title > h1 > yt-formatted-string"));
console.log(document.getElementById("title"));
});
Honestly, none of the lines was executed after applying this change.
After finding some advice on StackOverflow about the issue with "DOMContentLoaded," I modified the code as follows:
if (document.readyState !== 'loading') init();
else document.addEventListener('DOMContentLoaded', init);
function init() {
console.log(document.getElementById("title"));
console.log(document.querySelector("#title > h1 > yt-formatted-string"));
}
Unfortunately, the outcome remained the same:
<div id="title" class="style-scope ytd-watch-metadata">
null
If anyone could shed some light on what might be causing this problem and suggest a solution, it would be highly appreciated.