Skip to content

Commit

Permalink
Basic support for shadow-dom content_scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
cezaraugusto committed Nov 22, 2024
1 parent fe361a9 commit 7bd4312
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
4 changes: 4 additions & 0 deletions programs/cli/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,7 @@ interface ImportMetaEnv {
interface ImportMeta {
readonly env: ImportMetaEnv
}

interface Window {
__EXTENSION_SHADOW_ROOT__: ShadowRoot
}
42 changes: 41 additions & 1 deletion programs/develop/webpack/plugin-css/common-style-loaders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,41 @@ export interface StyleLoaderOptions {
loader?: string
}

function whereToInsertStyleTag(element: HTMLElement) {
// Function to check if the shadow root exists
const insertElement = () => {
// @ts-expect-error - global reference.
const shadowRoot = window.__EXTENSION_SHADOW_ROOT__

if (shadowRoot) {
shadowRoot.appendChild(element)
console.log('Element inserted into shadowRoot')
} else {
document.head.appendChild(element)
console.log('Element inserted into document.head')
}
}

// If the shadowRoot is already available, insert immediately
// @ts-expect-error - global reference.
if (window.__EXTENSION_SHADOW_ROOT__) {
insertElement()
return
}

// Use MutationObserver to wait for the shadow root to be available
const observer = new MutationObserver(() => {
// @ts-expect-error - global reference.
if (window.__EXTENSION_SHADOW_ROOT__) {
insertElement()
observer.disconnect() // Stop observing once the shadow root is found
}
})

// Observe changes to the `document.body` or `document.head`
observer.observe(document.body, {childList: true, subtree: true})
}

export async function commonStyleLoaders(
projectPath: string,
opts: StyleLoaderOptions
Expand All @@ -23,7 +58,12 @@ export async function commonStyleLoaders(
? miniCssLoader
: isUsingVue(projectPath)
? require.resolve('vue-style-loader')
: require.resolve('style-loader'),
: {
loader: require.resolve('style-loader'),
options: {
insert: whereToInsertStyleTag
}
},
{
loader: require.resolve('css-loader'),
options: {
Expand Down

0 comments on commit 7bd4312

Please sign in to comment.