Let’s say I am hosting site2.com
and have site2.com/frame.html
file that is simple as this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Site2.com frame</title> <style> body { background-color: yellowgreen; } </style> </head> <body id="site2-frame-body"> <h1>This is site2.com frame for 3rd party use</h1> <p>Lorem ipsum dolor sit amet consectetur adipisicing elit.</p> </body> </html>
Now say 3rd party website called site1.com
wants to embed this content via iframe
element like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Site1</title> </head> <body> <style> #site2frame { border: 2px solid red; } #site2frame-body { background-color: blue !important; } </style> <iframe id="site2frame" title="Inline Frame Example" width="300" height="200" src="https://site2.com:3002/frame.html"> </iframe> </body> </html>
So I get this result in the Chrome browser when I open site1.com
(ie. site1.com
is playing the role of the 3rd party site here, while site2.com
is site that hosts content to be embedded in inside iframe of other websites):
So the background of body
element inside the frame is yellowgreen
as set by the style in the site2.com/frame.html
. When I try to override that with blue
color as specified in the parent’s website site1.com:3002
this is not applied. I even used id selector with !important
attribute but that is not propagated to inside of the frame content. Note that I am able to style the iframe
element itself (with red border) but that is not my issue here.
So how can I enable this? Is there some standard way like enabling some http policy or setting some server headers site2.com
that tells browsers “please allow CSS styling on embedded frames from this origin”? Note that frame content is cross-origin.
Note: this dev environment is set by me for practicing by using hosts file to point both site1.com
and site2.com
to 127.0.0.1 and I am running two node express instances to simulate different servers.
Advertisement
Answer
You can’t style 3rd party iframes because they are protected by the ‘Same-origin Policy‘.
That being said you could try sending the URL of a stylesheet as a GET parameter, and have site2.com/frame.html
read this parameter and dynamically add it to its <head>
.
For example, site1.com
could create the iframe like so:
<iframe id="site2frame" title="Inline Frame Example" width="300" height="200" src="https://site2.com:3002/frame.html?css=externalstylesheet.css"> </iframe>
And site2.com/frame.html
could read the GET parameter, create a link
element with the href
set to the value of the parameter and append it to document.head
:
var css = new URLSearchParams(location.search).get('css'); var stylesheet = document.createElement("link"); stylesheet.rel = "stylesheet"; stylesheet.href= css; document.head.append(stylesheet);