Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I contain the styles of a Chrome Extension content script?

I'm working on a Chrome extension that injects some UI react components into a page.

The UI components come from react-mdl. Using them requires me to include a css file in the top of my project.

Unfortunately, once the css is injected into the page, the entire page's font is changed.

Is there a way to limit the scope of the css used by react-mdl such that it doesn't affect the page into which I'm injecting?

like image 797
Brandon Avatar asked Dec 19 '22 09:12

Brandon


1 Answers

Just posting this for posterity as accepted answer deserves credit, but if anyone finds themselves in a similar predicament, here is a snippet of the code that worked for me:

// my injected code
window.addEventListener('load', () => {
    const injectDiv = document.createElement('div')
    const shadowRoot = injectDiv.attachShadow({ mode: 'open' })

    // note inline use of webpack raw-loader, so that the css
    // file gets inserted as raw text, instead of attached to <head>
    // as with the webpack style-loader

    shadowRoot.innerHTML = // just using template string
      `
       <style>${require('raw-loader!app/styles/extension-material.css')}</style>
       <div id='shadowReactRoot' />
       `
    document.body.appendChild(injectDiv)
    ReactDOM.render(
          <App />,
          // note you have to start your query in the shadow DOM
          // in order to find your root
          shadowRoot.querySelector('#shadowReactRoot')
        )
})

Then, sure enough:

shadow DOM inside the document

like image 82
Brandon Avatar answered Dec 31 '22 02:12

Brandon