How to really isolate stylesheets in the Google Chrome extension?

As I’ve recently gone through the gauntlet of this issue, I want to share some information I think is valuable.

First, Rob W’s answer is correct. Shadow DOM is the correct solution to this problem. However, in my case not only did I need CSS isolation, I also needed JavaScript events. For example, what happens if the user clicks a button that lives within the isolated HTML? This gets really ugly with just Shadow DOM, but we have another Web Components technology, Custom Elements, to the rescue. Except that as of this writing there is a bug in chrome that prevents custom element in chrome extensions. See my questions here and here and the bug here.

So where does that leave us? I believe the best solution today is IFrames, which is what I went with. The article shahalpk linked is great but it only describes part of the process. Here’s how I did it:

First, create an html file and js file for your isolated widget. Everything inside these files will run in an isolated environment in an iframe. Be sure to source your js file from the html file.

//iframe.js
var button = document.querySelector('.my-button');
button.addEventListener('click', function() {
    // do useful things
});

//iframe.html
<style>
/* css */
</style>
<button class="my-button">Hi there</button>
<script src="https://stackoverflow.com/questions/12783217/iframe.js"></script> 

Next, inside your content script create an iframe element in javascript. You need to do it in javascript because you have to use chrome.extension.getURL in order to grab your iframe html file:

var iframe = document.createElement('iframe');
iframe.src = chrome.extension.getURL("iframe.html");
document.body.appendChild(iframe);

And that’s it.

One thing to keep in mind: If you need to communicated between the iframe and the rest of the content script, you need to chrome.runtime.sendMessage() to the background page, and then chrome.tabs.sendMessage from the background page back to the tab. They can’t communicate directly.

EDIT: I wrote a blog post detailing everything I learned through my process, including a complete example chrome extension and lots of links to different information:

https://apitman.com/3/#chrome-extension-content-script-stylesheet-isolation

In case my blog goes down, here’s the sources to the original post:

Blog post

Example source

Leave a Comment