Bra*_*don 4 css google-chrome-extension reactjs material-design-lite
我正在开发一个 Chrome 扩展程序,它将一些 UI 反应组件注入到页面中。
UI 组件来自react-mdl. 使用它们需要我在项目顶部包含一个css 文件。
不幸的是,一旦css注入页面,整个页面的字体都会改变。
有没有办法来限制的范围内css使用react-mdl,使得它不会影响我注入该页面?
只是将这个发布给后代作为公认的答案值得称赞,但如果有人发现自己处于类似的困境,这里是对我有用的代码片段:
// 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')
)
})
Run Code Online (Sandbox Code Playgroud)
那么,果然:
我认为你应该使用 Shadow DOM API。当您只需要将 UI 组件附加到网页时,这是一个很好的做法。
https://developers.google.com/web/fundamentals/getting-started/primers/shadowdom
| 归档时间: |
|
| 查看次数: |
1655 次 |
| 最近记录: |