Web Component that can request another HTML URL and inject it into it's shadow DOM

658 views Asked by At

I spent some time today with Lit trying to make a simple WebComponent that makes a HTTP GET to a URI, which returns a fully formed HTML document, and I want to inject said HTML document into the WebComponent's shadow DOM; basically this WebComponent acts as a simple proxy for embedding an externally hosted (but trusted) web snippet on my web page. I ran into a few problems:

  1. Lit considers all HTML unsafe, so i had to mark it with Lit's unsafeHTML directive.
  2. Then, I noticed none of the script or link tags in the injected HTML were being followed, so I parsed the incoming HTML as a HtmlDocument, located all the script/link tags, and "re-created" them using document.createElement(...) and returned them in my render(). I'm now noticing that images arent showing up either.

I don't like scraping scripts/links and re-creating them and jamming them into my web component anyhow, but I'm curious - what's the right way to approach this syndicating/consuming syndicated HTML pages/fragments?

Is this a solved problem w/ oEmbed already?

Is this simpler to do with a different WebComponent library?

This seems way harder than it should be at this point.

1

There are 1 answers

0
toto11 On

I think that it has little to do with WebComponents but rather with the HTML5 specs. lit-html uses innerHTML to create elements.

Script elements inserted using innerHTML do not execute when they are inserted

There are still ways to execute JS but this has little to do with your question.

unsafeHTML(`<img src="triggerError" onerror="alert('BOOM')">`)

Regarding the images, it may be a path issue?

This should work:

unsafeHTML(`<img src='http://placehold.it/350x350'>`)