Created
August 24, 2023 18:03
-
-
Save mwood23/c1812dd6bb116fcd742e421008478038 to your computer and use it in GitHub Desktop.
Web Component Shadow Root Pierer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ShadowStyler { | |
constructor(componentName) { | |
this.componentName = componentName; | |
this.element = document.querySelector(this.componentName); | |
this.shadowRoot = this.element?.shadowRoot; | |
} | |
setStyle(selector, styles) { | |
if (this.shadowRoot) { | |
this._applyStyle(selector, styles); | |
} else { | |
// If shadow root isn't available yet, queue the style change to be applied later. | |
let retryCount = 0; | |
const maxRetries = 50; // for a total of 5 seconds (50 retries x 100ms) | |
const retryInterval = setInterval(() => { | |
this.shadowRoot = this.element?.shadowRoot; | |
if (this.shadowRoot || retryCount >= maxRetries) { | |
clearInterval(retryInterval); | |
if (this.shadowRoot) { | |
this._applyStyle(selector, styles); | |
} else { | |
console.warn('Max retries reached. Shadow root not found.'); | |
} | |
} | |
retryCount++; | |
}, 100); | |
} | |
} | |
_applyStyle(selector, styles) { | |
const elements = this.shadowRoot.querySelectorAll(selector); | |
if (!elements.length) { | |
console.warn(`No elements found for selector: ${selector}`); | |
return; | |
} | |
Object.entries(styles).forEach(([property, value]) => { | |
elements.forEach(element => { | |
element.style[property] = value; | |
}); | |
}); | |
} | |
} | |
// Usage: | |
const styler = new ShadowStyler('form-embed'); | |
styler.setStyle('.myClass', { background: 'red' }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment