如何包含 Chrome 扩展内容脚本的样式?

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

我正在开发一个 Chrome 扩展,可以将一些 UI 反应组件注入页面。

我项目顶部的UI个组件come from react-mdl. Using them requires me to include a css file

不幸的是,一旦将 css 注入到页面中,整个页面的字体都会改变。

有没有办法限制 react-mdl 使用的 css 的范围,使其不影响我正在注入的页面?

我认为你应该使用 Shadow DOM API。对于那些只需要将 UI 组件附加到网页的情况,这是一个很好的做法。

https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom

只是将此作为已接受的答案发布给后代,值得称赞,但如果有人发现自己处于类似的困境,这里有一段对我有用的代码:

// 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')
        )
})

那么,果然:

this other SO post中所述,也支持<link>标签,所以可以简单地做如下操作:

const injectedDiv = document.createElement('div');
const shadowRoot = injectedDiv.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = `\
   <link rel="stylesheet" type="text/css" href="${chrome.extension.getURL("bootstrap.min.css")}"></link>\
   <link rel="stylesheet" type="text/css" href="${chrome.extension.getURL("whatever.css")}"></link>\
`;
document.body.appendChild(injectedDiv);

备注:

  1. 获取扩展的本地资源 url 需要使用 chrome.extension.getURL,参见例如in this answer
  2. 必须在 manifest.json 中的 web_accessible_resources 属性 下声明链接的 .css 资源(否则,您将获得 this error