Embed LiveView inside ShadowDOM

Hi all! I come with a proposal to create LiveViews inside the shadow DOM. At Doofinder, we have experience building embeddable LiveView apps, and we think it is a valuable addition to the ecosystem, as it allows for fast interaction widgets.

Why

The main problem with multiple LiveViews from different origins coexisting in the same DOM is duplication of events and elements. If we leverage the shadow DOM, we could bypass these limitations while also allowing for easier communication between the host page and the LiveView widgets.

Why use shadowDOM and not <iframe>

While there has already been discussion about doing this with <iframe>, We think the Shadow DOM is more adecuate for the following reasons:

  • SEO. If the LiveView widget is loaded with the page, the content would count to the host page, not the origin of the LiveView as it would happen with <iframe>.
  • Performance. No need to load a full DOM.
  • Session cookie: Safari conflicts with <iframe> and cookies. ref
  • Better comunication with host page and with other apps. No need for postMessage().

It is worth noting that I haven’t mentioned anything about WebComponents, because the goal of this is not adding support for them. The approach we present would only mean encapsulating the DOM where the LiveView lives. Here there was a related discussion, and I think some of the problems exposed there could be solved.

What would change

This feature would be a new way to use LiveView and it would not affect regular LiveViews

Doing a quick prototype I identified some areas of work:

  1. Add a way to configure a LiveView to create a shadow DOM.
  2. Places where document is used to find a DOM element should support using the shadowRoot.
  3. Event listeners need to be added to the shadowRoot instead of window.

We volunteer to work on this and implement it.


So what are your thoughts on this? Would you benefit from this feature? Are the core maintainers open to us working on this?

10 Likes

Interesting idea! It does mean the “host page” must be a Phoenix LiveView app, right? Unlike an iframe, I’m understanding you’re not interested in embedding LiveViews into third-party pages but pages under your control, is that right?

:bulb:Reminds me of the idea of “islands” in the JS ecosystem.

The goal is to make it work under any type of host page, also regardless of who owns the host page!

1 Like

Searching for something unrelated on the forum I accidentally found Running LiveView inside a web component with shadow DOM and thought it could be a reference point for this conversation.

3 Likes

Hey @victor23k,

I’d be happy to review a PR that explores this!

Thanks! I’ll work on that. We had planned to open source a library with the functionality described that we use internally. The goal was to see if more people are interested in it. It can serve as a preview until the PR hopefully gets merged to LiveView.

1 Like