7 Reasons To Use Iframes in Chrome Extensions

In my experience, iframes are a very powerful tool in chrome extension development. When used wisely, they can save a lot of time and effort, make the extnesion secure and reliable. I strongly recommed it over solutions like Shadow DOM or custom elements.

1 - Security

When embedding a a UI component on a third-party website without iframes, that website has access to the interface, and to all the data that is being displayed. That website can also trigger clicks, and updates. It can read usernames and passwords while a user is loggin in or signing up.

But if you wrap that UI with an iframe - the website whre it has been injected can't read what's inside. Just make sure that the iframe's src attribute has the extension origin, not the origin of the injected page.

2 - Style encapsulation

If you inject an iframe into a page - you don't have to worry that the CSS styles inside that page will break the way your UI looks. Because styles inside an iframe are separated from styles in the injected page.

3 - The possibility to inject remote iframes

If you have a web application already, and would like to build a chrome extension for it - using iframes is an amazing tool. You can just inject an iframe of that web app in any page instead of re-implementing the whole UI from ground up. Just remember to first wrap that iframe in another iframe with src attribute pointing to a chrome-extension://* URL.

4 - Testability

If you implement your UI in an iframe - it is very easy to then open it as a separate webpage to test the UI, instead of reproducing the steps to opening or injecting a DIV into a page.

5 - View and logic separation

By delegating view to an iframe and implementing logic in a content script you are doing view and logic separation - which is a good software development practice.

6 - Reusability

You can reuse the same iframe in a browser action popup, in an injected element, or in a devtools panel. Don't create multiple pages and stop code duplication.

7 - Access to chrome APIs

Content scripts don't have access to such chrome extension APIs as tabs or cookies, but scripts inside an iframe do. Use iframes to gain access to those APIs without sending a request to a background script.