TrustedHTML - Why Can't I Create Web Components from the Console?

Roja GnanavelRoja Gnanavel
1 min read

I came across the TrustedHTML API while working with Web Components in the Lit framework. Being a lazy developer, I prefer testing things directly in the browser console instead of creating separate files. During one of these experiments, I ran into an error when trying to use innerHTML in Web Components. It turns out this is due to browser security measures designed to prevent harmful code injection, like XSS attacks.

Curious, I started reading about the TrustedHTML API, and I found it surprisingly interesting. It’s a feature I hadn’t explored before, but it’s clear how important it is for keeping Web Components secure, especially when working with Shadow DOM.

What is the TrustedHTML API?

Browsers use a safety feature called the TrustedHTML API to keep websites safe. This feature makes sure that only safe HTML content can be added to a webpage, especially in Web Components.

  • Why does this matter for Web Components? Web Components use something called Shadow DOM, which keeps them separate from the rest of the webpage. The browser wants to make sure that no harmful code can be inserted into these protected areas.

To know more about web Components and TrustedHTML API. Please go through the official docs.

Web Components: https://developer.mozilla.org/en-US/docs/Web/API/Web_components

Shadow DOM: https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_shadow_DOM

TrustedHTML API: https://developer.mozilla.org/en-US/docs/Web/API/TrustedHTML

0
Subscribe to my newsletter

Read articles from Roja Gnanavel directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Roja Gnanavel
Roja Gnanavel

Seasoned Web Developer | 8+ Years of Experience As a passionate tech enthusiast, I've spent years devouring industry insights. But, I realized that my laziness was holding me back from sharing my knowledge. No more! Inspired by Instagram's visual storytelling, I'm now documenting my tech adventures on Hashnode. Follow me for valuable tech insights, and let's grow together!