Add CSS to an iframe

Page section: playground

The idea of this page is to show how CSS can be injected into an iframe using the JavaScript contentDocument to add <style> tags to the body of the iframe.

A second idea for this page was to use Hugo to embed this page’s current js file or files into the page content using {{ .GetPage }} or {{ .Page.Resources }}. The latter is working with the page as a Hugo leaf bundle.

This can be added to any page using the show-js.html shortcode.

iframe limitations and CORS

The CSS that can be applied to an iframe is limited to the block. However using JavaScript it’s possible to inject some CSS to style the contents of the iframe. However this will only work with local files by default which is less use. Obviously if they’re local you can add CSS directly to such files anyway.

This won’t work on files from a different origin (ie. URL) because by default they will be protected by CORS: cross origin resource sharing. CORS is a security feature of the browser but the default behaviour can be overridden in the http headers.

Adding some CSS to this iframe

The iframe has a number of styles already set but the color of the the paragraphs, list and heading cannot be changed from outside the file.

This is based on code from redstapler.co

window.onload = function() {
   let myiFrame = document.getElementById("myiFrame");
   let doc = myiFrame.contentDocument;
   doc.body.innerHTML = doc.body.innerHTML + '<style>/******* Put your styles here *******</style>';
};

Rather than add the CSS to the <body> I added it to the <head> of the document using doc.head.innerHTML instead of doc.body.

The key property is that of contentDocument. You can see this in the console.

File: iframe.js

Shows the iframe.js file exactly as it is.

const iframeBtn = document.getElementById('iframe-btn'); console.log('iframe.js ere'); iframeBtn.addEventListener('click', (e) => { const myIframe = document.getElementById('iframe-example'); const doc = myIframe.contentDocument; const css = ` <style> h1 { color: orangered; font-weight: 500; } p, ul { color: yellow; } </style>`; doc.head.innerHTML = doc.head.innerHTML + css; e.target.textContent = 'BAM!!'; console.log(doc); });

Markdownified version

Page resources:

The full resources for this page (leaf bundle) are: