refactor: improve startShadowDOMStyleInjection()

This commit is contained in:
Hakadao
2024-09-14 00:22:52 +08:00
parent d9bc3b546c
commit 5c1dc39520

View File

@@ -212,34 +212,41 @@ function injectApp() {
app.mount(root)
}
function injectStyleToShadowDOM(shadowRoot: ShadowRoot) {
if (!shadowRoot.querySelector('style[data-bewly-style]')) {
const styleEl = document.createElement('style')
styleEl.setAttribute('data-bewly-style', 'true')
// Reset the theme color to ensure the theme color is updated
styleEl.textContent = `
@import url(${browser.runtime.getURL('dist/contentScripts/style.css')});
* {--bew-theme-color: ${settings.value.themeColor};}`
shadowRoot.appendChild(styleEl)
}
}
function injectStylesRecursively(root: Document | ShadowRoot) {
if (root instanceof ShadowRoot) {
injectStyleToShadowDOM(root)
}
root.querySelectorAll('*').forEach((element) => {
if (element.shadowRoot) {
injectStylesRecursively(element.shadowRoot)
}
})
}
function startShadowDOMStyleInjection() {
if (isSupportedPages()) {
setInterval(() => {
injectStylesRecursively(document)
}, 1000)
}
function injectStylesRecursively(root: Document | ShadowRoot) {
if (root instanceof ShadowRoot) {
injectStyleToShadowDOM(root)
}
root.querySelectorAll('*').forEach((element) => {
if (element.shadowRoot) {
injectStylesRecursively(element.shadowRoot)
}
})
}
function injectStyleToShadowDOM(shadowRoot: ShadowRoot) {
if (!shadowRoot.querySelector('style[data-bewly-style]')) {
const styleEl = document.createElement('style')
styleEl.setAttribute('data-bewly-style', 'true')
styleEl.textContent = `
@import url(${browser.runtime.getURL('dist/contentScripts/style.css')});
`
if (settings.value.adaptToOtherPageStyles) {
// Reset the theme color to ensure the theme color is updated
styleEl.textContent += `
* {
--bew-theme-color: ${settings.value.themeColor};
}
`
}
shadowRoot.appendChild(styleEl)
}
}
}