I am working on my google chrome extension and i need to know how to add the button under the youtube video. Here is my code
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.status === 'complete') {
chrome.tabs.get(tabId, function(tab) {
if (tab.url.includes('https://www.youtube.com/watch')) {
chrome.scripting.executeScript({
target: { tabId: tabId },
function: () => {
// Function to create and inject button
function addButton() {
const button = document.createElement('button');
button.textContent = 'Click Me!';
button.style.backgroundColor = '#ff0000';
button.style.color = '#ffffff';
button.style.padding = '10px';
button.style.border = 'none';
button.style.cursor = 'pointer';
button.addEventListener('click', function () {
alert('You pressed the button!');
});
return button;
}
// Function to inject button if it doesn't exist
function injectButton() {
const videoContainer = document.querySelector('#info');
const existingButton = document.querySelector('#info button');
if (videoContainer && !existingButton) {
videoContainer.append(addButton());
}
}
// Start observing
const targetNode = document.querySelector('body');
const observerOptions = {
childList: true,
attributes: true,
subtree: true
};
const observer = new MutationObserver(injectButton);
observer.observe(targetNode, observerOptions);
// Inject button initially if possible
injectButton();
}
});
}
});
}
});
console.log("working")
It is background.js file
here is my manifest.json
{
"manifest_version": 3,
"name": "YouTube Button Extension",
"version": "1.0",
"permissions": ["scripting", "webNavigation"],
"host_permissions": ["https://www.youtube.com/*"],
"background": {
"service_worker": "background.js"
}
}
My background.js file working, but the button is not showing. There is no errors. I tried to ask ChatGPT but he didn't give me a good answer. Help, please