简体   繁体   English

反向阴影 dom,防止 css 和 js 从子树泄漏到文档

[英]inverse shadow dom, prevent css and js leaks from subtree to document

There is dynamic HTML content that I would like to include in my page.我想在我的页面中包含动态 HTML 内容。 This is only HTML and CSS, no Javascript.这只是 HTML 和 CSS,没有 Javascript。

I have some global CSS styles and custom JS logic that needs to be applied to this dynamic content.我有一些全局 CSS 样式和自定义 JS 逻辑需要应用于此动态内容。 Which means that I can't simply encapsulate it in an iframe.这意味着我不能简单地将它封装在 iframe 中。 It should be in the same DOM as everything else.它应该和其他所有东西都在同一个 DOM 中。

But the dynamic content can define its own CSS, which I don't want to be applied to the global scope.但是动态内容可以定义自己的CSS,我不想应用到全局范围。 Therefore I can't just set it as innerHTML on some div.因此,我不能在某些 div 上将其设置为 innerHTML。

Here is a simple example, which sets it as innerHTML and pollutes global CSS ( jsfiddle ):这是一个简单的例子,它将它设置为innerHTML并污染全局CSS( jsfiddle ):

<!--this style needs to be global-->
<style>p {font-size:24px;}</style>
<p>Welcome, please take a look at this dynamic content:</p>

<!--custom elements need to be added here-->
<div id='placeholder'></div>


<script>
// the style in here must not be global
const dynamic=`
<p>dynamic html with fancy style :)</p>
<style>p {color:blue;}</style>
`
$("#placeholder").html(dynamic)
</script>

Now, with the shadow dom a similar problem is solved :现在,使用shadow dom 解决了类似的问题

Shadow DOM lets you place the children in a scoped subtree, so document-level CSS can't restyle the button by accident, for example.例如,Shadow DOM 允许您将子项放置在作用域子树中,因此文档级 CSS 不会意外地重新设置按钮的样式。

What I'm looking for is something like an inverse shadow DOM.我正在寻找的是类似于反向阴影 DOM 的东西。 Instead of shielding a local subtree from global styles, I want to shield the global styles from the local subtree.我不想屏蔽全局样式的本地子树,而是屏蔽本地子树的全局样式。 Is that possible?那可能吗? An important constraint is that custom javascript logic which also resides in global scope.一个重要的限制是自定义 javascript 逻辑也驻留在全局范围内。 The dynamic HTML should be accessible to jQuery, just like other elements. jQuery 应该可以访问动态 HTML,就像其他元素一样。

Shadow DOM CSS isolation is two-ways. Shadow DOM CSS 隔离有两种方式。 So with this technique you can "shield the global styles from the local subtree":因此,使用这种技术,您可以“从本地子树中屏蔽全局样式”:

 // the style in here must not be global const dynamic=` <p>dynamic html with fancy style :)</p> <style>p {color:blue;}</style> ` placeholder.attachShadow( { mode: 'open' } ) .innerHTML = dynamic
 /*this style needs to be global*/ p {font-size:24px;}
 <p>Welcome, please take a look at this dynamic content:</p> <!--custom elements need to be added here--> <div id='placeholder'></div>

About JS, if you put it in a custom element class it won't leak anywhere else.关于 JS,如果你把它放在自定义元素类中,它不会泄漏到其他任何地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM