Shirt designs

Shadow DOM and browser extensions

12-03-2023

Recently I implemented new a third party feature (one of Google's betas) to the project I was working on. Even though it had many intriguing edges. One caught my attention, their usage of Shadow DOM. Even though it gave me some hard time to do what I was supposed to do. I saw the potential it had in other areas due to my some previous experiences.


What is Shadow DOM?

You can think of Shadow DOM as a mini, encapsulated DOM inside your regular one. Shadow DOM can not affect your regular one and vice versa. You can see the following image to visualize it a bit better.


Shadow DOM represantion
Source: MDN web docs Shadow DOM

As you can see, this gives you some encapsulated space to play in. One of the first usage areas I thought of when I saw this was browser extensions. When building a browser extension you often interact with many other websites that you know nothing about. So having an encapsulated environment to work removes some burden from you since you won't be thinking about either your code getting messed up from someone else's styles or messing someone else's code with your event listeners.


Fundamentals

You can use Element.attachShadow() to add a shadow root to any element. This takes as its parameter an options object that contains an option mode with the value on or off. Which decides if people will be able to access your shadow DOM from outside or not.


const shadowOpen = elementRef.attachShadow({ mode: "open" });
const shadowClosed = elementRef.attachShadow({ mode: "closed" });

The rest is same with modifying your regular DOM with Javascript. You can use all methods available to alter it.