Skip to content
Advertisement

Let 3rd party change styles of an iframe of my site

Let’s say I am hosting site2.com and have site2.com/frame.html file that is simple as this:

JavaScript

Now say 3rd party website called site1.com wants to embed this content via iframe element like this:

JavaScript

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):

enter image description here

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:

JavaScript

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:

JavaScript

Edit pedantic-euclid-m120j

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement