I am trying to build and extension for youtube for which I need to manipulate its DOM. The Dom manipulation thing works but not the first load but after reloading the page for once.
The code for my script file:
import React from "react";
import { createRoot } from "react-dom/client";
import App from "./src/App";
import "./src/index.css";
declare const chrome: any;
if (typeof browser === "undefined") {
var browser = chrome;
}
class Main extends React.Component {
render() {
return (
<div className={'my-extension'}>
<App />
</div>
)
}
}
function addReactApp() {
const sideBox = document.getElementById("secondary");
const sideBox_inner = document.getElementById("secondary-inner");
const videoPlayer = document.getElementsByClassName("html5-video-container");
console.log("videoPlayer",videoPlayer)
if (sideBox && sideBox_inner && videoPlayer) {
const app = document.createElement("div");
app.id = "tubechat-ai";
sideBox.prepend(app);
const container = document.getElementById("tubechat-ai");
if (container) {
const root = createRoot(container);
root.render(
<React.StrictMode>
<Main />
</React.StrictMode>
);
}
} else {
console.log("Not all required elements are present.");
}
}
browser.storage.sync.get("ytrvp-manipulating-dom", function (items) {
if (!browser.runtime.error) {
let observer = new MutationObserver((mutations) => {
for (let mutation of mutations) {
for (let node of mutation.addedNodes) {
const shouldAddReactApp = node instanceof HTMLElement && node.tagName === "DIV" && node.id === "secondary";
shouldAddReactApp ? addReactApp() : console.log("No tags found in the added node");
}
}
});
observer.observe(document, { childList: true, subtree: true });
} else {
console.log("Runtime error occurred");
}
});
Manifest File for extension :
{
"manifest_version": 3,
"name": "Tubechat.ai",
"version": "1.0.0",
"permissions": [
"activeTab",
"storage",
"scripting",
"webNavigation",
"tabs",
"notifications"
],
"host_permissions": [
"http://www.youtube.com/*",
"https://www.youtube.com/*"
],
"action": {
"default_popup": "index.html",
"default_icon": {
"16": "my-assets/logo.png",
"48": "my-assets/logo.png",
"128": "my-assets/logo.png"
}
},
"icons": {
"16": "my-assets/logo.png",
"48": "my-assets/logo.png",
"128": "my-assets/logo.png"
},
"content_scripts": [
{
"matches": ["*://www.youtube.com/*"],
"js": ["content.js"],
"css": ["my-assets/index.css"]
}
],
"background": {
"service_worker": "background.js"
}
}
I have tried to change the manifest by putting the run_at
tag in the content script but that also didn’t work