Search code examples
javascripthtmlcssshadow-dom

How to include 3rd party HTML snippet in isolation on web page?


I have to make a call from my Web app to a 3rd party web service, which will will return an HTML document, that i want to in-turn include on my page; basically consuming syndicated self-contained promotional "chunks" of html (which include the CSS to layout/style them as the syndicator intended).

Is there a way to do this and isolate the HTML without using iframes (since its hard to tell how to size the iframe)? I'd like to ensure that 1) the incoming CSS/JS doesn't impact the rest of the page, and vice versa - i don't want the greater page's styles to impact the view of the promo content.

Is there something that can be done with Shadowdom/shadowdom-polyfills? or Web components?

It seems like the Twitter/Instagram are able to do do this someone?


Solution

  • With Shadow DOM you can isolate CSS.

    promo.attachShadow( { mode: 'open' } )
         .innerHTML = `
            <style> 
              div { color: red ; }
            </style>
            <div>Isolated CSS style</div>`
    <div id="promo"></div>

    Unfortunately you won't be able to isolate Javascript.

    For Javascript isolation, the only way is <iframe> with the sandbox attribute as stated by @zero298.