使用 document.getElementById 将 ShadowDom 中的特定元素暴露给外部 JS [英] Expose specific element in ShadowDom to external JS using document.getElementById
问题描述
我有一个 v0/Polymer 1 Web 组件,我要升级到 v1/Polymer 2.这个 Web 组件动态构建一个 URI 来加载外部 JavaScript 文件.外部 JavaScript 文件运行并将 加载到我的组件的
document.getElementById
以将
加载到指定的 中.我已经搜索过,但没有找到强制将
元素暴露/放置在 shady DOM 中的方法.我已经读过,如果我设计的组件没有 shadow DOM,则不会显示任何内容.无论如何我可以使用外部脚本(第三方)将其更新到 web components v1/Polymer 2 仍然使用 document.getElementbyId
来修改 <div>
在 Web 组件内部?
更新我发现我可以使用 <script>window.ShadyDOM = { force: true };</script>
或 <script src="/bower_components/webcomponentsjs/webcomponents-lite.js" shadydom></script>
但是我仍然无法通过 ID 访问该元素,并且我不想强制所有其他 webcomponents 使用 shady DOM.仍在寻找可能性.
解决方案 我必须做的是在我的 Web 组件模板中放入一个
.当我声明自定义元素时,我必须在其中嵌套一个
,如下所示:
我正在使用 this.appendChild()
其中 this
是自定义元素.元素中的 现在可以通过 document.getElementById()
访问,一旦它被分配了 id
属性.I have a v0/Polymer 1 web component that I am upgrading to v1/Polymer 2. This web component dynamically builds a URI that loads an external JavaScript file. The external JavaScript file runs and loads an <iframe>
into a <div>
of my component. This external JS contains document.getElementById
to load the <iframe>
into the specified <div>
.
I have searched and haven't found a way to force the <div>
element to be exposed/placed in the shady DOM. I have read that if I design the component without a shadow DOM nothing will be displayed.
Is there anyway I can update this to web components v1/Polymer 2 with the external script (third party) still using document.getElementbyId
to modify a <div>
inside the web component?
UPDATE
I have found that I can force webcomponents to use the shadow dom using <script>window.ShadyDOM = { force: true };</script>
or <script src="/bower_components/webcomponentsjs/webcomponents-lite.js" shadydom></script>
however I still cannot access the element by ID and I do not want to force all other webcomponents to use the shady DOM. Still looking for possibilities.
解决方案 What I had to do was put a <slot></slot>
inside my Web Components template. When I declare the custom element, I have to nest a <div>
inside of it like so: <custom-element><div></div></custom-element>
which I am doing using this.appendChild()
where this
is the custom element. The <div>
inside my element can now be accessed by document.getElementById()
once it is assigned an id
attribute.
这篇关于使用 document.getElementById 将 ShadowDom 中的特定元素暴露给外部 JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文