I am creating a chrome extension that inserts an element in front of every google search result. I am doing this by looping over all div’s with an id of “a h3” on the google search page.
However I am having a problem with getting my injected element to show up on the left side of the results, i can only seem to be able to get it to work overlapping the result. Is there a way to get it so it injects the square in front of the result?
the script that injects the square can be found below:
import React, { useEffect, useRef, useState } from "react"
function ContentScript() {
const indexRef = useRef(1)
useEffect(() => {
const addShadowDivs = () => {
const searchResultDivs = document.querySelectorAll("a h3")
searchResultDivs.forEach((div) => {
if (div.parentElement.querySelector('[data-extension-shadow="true"]')) {
console.log("Shadow host already exists for this div")
return
}
const shadowHost = document.createElement("div")
shadowHost.setAttribute("data-extension-shadow", "true")
shadowHost.style.position = "relative"
const shadowRoot = shadowHost.attachShadow({ mode: "open" })
const shadowContent = document.createElement("div")
shadowContent.id = indexRef.current.toString()
shadowContent.className = "content-shadow-dom"
shadowContent.style.float = "left"
shadowContent.style.width = "40px"
shadowContent.style.height = "100px"
shadowContent.style.position = "absolute"
shadowContent.style.left = "-10px"
shadowContent.style.zIndex = "100000"
shadowContent.style.textAlign = "center"
shadowContent.style.backgroundColor = "#f0f0f0"
indexRef.current += 1
shadowRoot.appendChild(shadowContent)
console.log(div.parentElement)
div.parentNode.insertBefore(shadowHost, div)
})
}
addShadowDivs()
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (mutation.type === "childList") {
addShadowDivs()
}
})
})
observer.observe(document.body, { childList: true, subtree: true })
return () => observer.disconnect()
}, [])
return null
}
export default ContentScript
Tried multiple things like adding the shadowContent to different parts of the original DOM and changing all possible values on the shadowContent
2