0

I have one script, outside the ShadowDom, that attaches a shadowRoot to an element and fills the Shadow Dom. The mode of shadowRoot is closed. I am not adding the

var variable = element.attachShadow({mode:'closed'}) 

variable to the window scope, it's within a function.

A script within the Shadow Dom needs to access other elements of that same Shadow Dom. Is there a way to do that? I tried,

document.currentScript.parentNode 

But document.currentScript returns null.

1 Answer 1

2

Why are you storing CODE in the shadowDOM? Code is not sandboxed like HTML and CSS when inside shadowDOM. It is still run at a global level. This is different than how the <iframe> works.

If you are going to this level of attempted segregation of code then just use a real WebComponent and do everything in that class.

If you still have to continue to do it how you are doing it then you need to have a way to pass variable (The shadowRoot variable) into the code you are placing in the shadowDOM.

UPDATE - Aug 3, 2020

If other code needs to access a closed shadow DOM then the code that created the shadowRoot needs to save off the shadowRoot as a variable and then pass that variable to the other functions. Or, you need to create a closed scope within JavaScript and store the shadowRoot in that scope. If all other functions are within that scope then they will have access to the variable that points to the shadowRoot.

Below is some EXAMPLE code that shows how to create a scope.

const publicInterface = (function() { var shadowRoot; function createShadowDom() { shadowRoot = ... } function doSomethingElse() { let a = shadowRoot.querySelector('.something'); if (a) { } } return { createShadowDom, doSomethingElse } })(); publicInterface.createShadowDom(); publicInterface.doSomethingElse();

The variable shadowRoot is protected inside the scope and can not be accessed by any outside code. But any function inside the scope, like createShadowDom and doSomethingElse can access shadowRoot.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.