简体   繁体   中英

How to style content of iframe on different domain?

I have a widget hosted on one domain and multiple websites which use an iframe to display the widget. I would like the content of the iframe to be styled depending on the parent website, but I know that due to the Same Origin Policy the parent website cannot manipulate the content from another domain.

I have access to both the widget and the parent websites and was wondering what is the best way to change the style of the widget depending on the parent website? I would prefer a method that would mean if a new website needed to include the iframe or a existing website changed their styling I would not have to change the widget.

Would passing the location of the parent website's stylesheet through to the widget and using that to style the widget be a feasible idea and what is the best way to do this if it is?

On you server where the widget is hosted you can get the page from where the request is coming by using (if you use php):

$_SERVER["HTTP_REFERER"]

Based on that you can use different styles for the widget.

I would suggest creating a web service on the server which your widget is located that returns CSS based on a querystring parameter. The widget iframe can load externally located assets provided that they are defined explicitly in the HTML and not dynamically appended to the DOM (think about Google hosted JavaScript libs such as jQuery and the associated CSS).

Another solution, assuming you are using modern browser, you could use window.postMessage

This API allows you to dispatch events (and data along with it... such as a CSS string) from the parent window to the child window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM