【问题标题】:Rename var document. Run Js inside shadow root重命名 var 文档。在 shadow root 中运行 Js
【发布时间】: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


【解决方案1】:

所以我想出了以下解决方案:

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 内的元素范围。

【讨论】:

    猜你喜欢
    • 2018-10-02
    • 1970-01-01
    • 2014-12-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    相关资源
    最近更新 更多