【发布时间】:2021-07-26 03:29:10
【问题描述】:
我在网页中嵌入了一些 HTML 内容,我希望它与外部 CSS 隔离。我的用户能够动态创建 HTML 内容,这些页面可以包含一些简单的 JS。 我一直在尝试在影子根中运行这些 JS。由于 JS 是在用户创建页面时动态创建的,因此我需要一种方法来使在 shadowroot 中运行代码成为可能。我添加内容如下:
const header = document.createElement('header');
const shadowRoot = document.createElement('body')
shadowRoot.innerHTML = pageContent
var script = document.createElement('script')
script.textContent = `document.querySelectorAll('#ii0b7a'); document.createElement(........`
shadowRoot.appendChild(script)
header.attachShadow({
mode: 'open'
}).appendChild(shadowRoot)
document.getElementById('div-box-one').appendChild(header)
到目前为止一切顺利,但代码无法正确运行,因为脚本正在访问文档元素而不是 shadowRoot。所以我应该首先访问 shadowroot,然后我才能访问其中的元素。为此,我将 js 代码包装在一个函数中,并像这样重命名文档变量:
(function(document) {
// code here
}(document.getElementById('shadow_root').shadowRoot));
但是这种方法不能正常工作,因为在某些情况下我必须使用函数“document.createElement”,这会引发错误。
我的问题是:如何仅在需要时重命名文档变量。例如
document.querySelectorAll('#') = document.getElementById('shadow_root').shadowRoot.querySelectorAll('#')
document.createElement = document.createElement
我知道在 shadowRoot 中使用库几乎是不可能的,而 iframe 是另一种解决方案,但 iframe 给我带来了其他问题。 (shadow-dom library)
是否有可能实现我想要以某种方式重命名文档变量?
【问题讨论】:
-
这能回答你的问题吗? stackoverflow.com/questions/53698654/…
-
没有。脚本运行正常。问题是脚本内部的元素是使用 document.querySelector 等访问的。这不会在 shadowRoot 中找到元素,这就是我重命名文档变量的原因。
-
你能添加一个工作的sn-p吗...因为你在做奇怪的代码。你将元素添加到正文,然后将元素移动到标题。标题在哪里?如果它最初在正文中,则将其删除 bij pageContent
-
工作代码笔示例:codepen.io/gabgran/pen/NWdQoMb 查看节点列表如何在控制台上回显,错误仅在尝试创建元素时显示
标签: javascript html jquery shadow-dom