This is in my manifest.json file (for the purposes of a chrome extension):
"content_scripts": [ {
"world": "MAIN",
"matches": ["https://www.youtube.com/*"],
"js": ["src/contentScript.js"]
} ],
"web_accessible_resources": [
{
"resources": [
"assets/youtube.png",
"youtube.png",
"contentScript.js"
],
"matches": ["https://*.youtube.com/*"]
}
This is in my content scripts file:
const newVideoLoaded = async () => {
const askButtonExists = document.querySelector(".ytp-button.question-btn");
if (!askButtonExists) {
const button = document.createElement("img");
button.src = chrome.runtime.getURL("../assets/youtube.png");
button.className = "ytp-button.question-btn";
button.title = "Click to Ask Questions";
youtubeControlBar = null;
youtubePlayer = null;
document.addEventListener("DOMContentLoaded", function() { // waiting for fully loaded page
youtubeControlBar = document.getElementsByClassName("ytp-left-controls")[0];
youtubePlayer = document.getElementsByClassName('video-stream')[0];
console.log(youtubeControlBar, youtubePlayer);
});
if (youtubeControlBar && youtubePlayer) {
youtubeControlBar.appendChild(button);
button.addEventListener("click", addButtonHandler);
} else {
console.error("YouTube control bar or player not found");
}
}
};
I am running the chrome extension (locally) and the chrome extension’s console shows the control bar and the player are undefined. However, when I run getElementsByClassName() in the YouTube console independently it runs just fine.
I have tried looking on Stack Overflow – and have tried some solutions, but none seem to be working.
Any help would be appreciated!
I tried various solutions from this link specifically – /questions/9515704/access-variables-and-functions-defined-in-page-context-from-an-extension/9517879#9517879
None seemed to be working. Expected to actually get the YouTube player, but they are undefined. I need these elements so we can pause/play the video through our extension.
Annoark is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.