How to apply CSS to iframe?

How to apply CSS to iframe?

As many answers are written for the same domains, I’ll write how to do this in cross domains.

First, you need to know the Post Message API. We need a messenger to communicate between two windows.

Here’s a messenger I created.

/** * Creates a messenger between two windows * which have two different domains */ class CrossMessenger { /** * * @param {object} otherWindow – window object of the other * @param {string} targetDomain – domain of the other window * @param {object} eventHandlers – all the event names and handlers */ constructor(otherWindow, targetDomain, eventHandlers = {}) { this.otherWindow = otherWindow; this.targetDomain = targetDomain; this.eventHandlers = eventHandlers; window.addEventListener(“message”, (e) => this.receive.call(this, e)); } post(event, data) { try { // data obj should have event name var json = JSON.stringify({ event, data }); this.otherWindow.postMessage(json, this.targetDomain); } catch (e) {} } receive(e) { var json; try { json = JSON.parse(e.data ? e.data : “{}”); } catch (e) { return; } var eventName = json.event, data = json.data; if (e.origin !== this.targetDomain) return; if (typeof this.eventHandlers[eventName] === “function”) this.eventHandlers[eventName](data); } }

Using this in two windows to communicate can solve your problem.

In the main windows,

var msger = new CrossMessenger(iframe.contentWindow, “https://iframe.s.domain”); var cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join(‘n’); msger.post(“cssContent”, { css: cssContent })

Then, receive the event from the Iframe.

In the Iframe:

var msger = new CrossMessenger(window.parent, “https://parent.window.domain”, { cssContent: (data) => { var cssElem = document.createElement(“style”); cssElem.innerHTML = data.css; document.head.appendChild(cssElem); } })

See the Complete Javascript and Iframes tutorial for more details.

Source

Leave a Reply