如何解决重命名 var 文档在 shadow root 中运行 Js
我在网页中嵌入了一些 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)
是否有可能以某种方式重命名文档变量来实现我想要的?
解决方法
所以我想出了以下解决方案:
function documentParse() {
var element = document.getElementById('shadow_root').shadowRoot
element.createElement = function createElement(type) {
return document.createElement(type)
}
element.head = document.head
return element
}
script.textContent = `(function(document) {
//script source text
}(documentParse()));`
....
以这种方式包装脚本将使对文档的每次搜索都进入 shadowroot dom 内的元素范围。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。