问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/47061676/expose-specific-element-in-shadowdom-to-external-js-using-document-getelementbyi