简体   繁体   English

如何在不同的域上设置iframe的内容样式?

[英]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. 我有一个托管在一个域和多个网站上的小部件,它们使用iframe来显示小部件。 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. 我希望根据父网站设置iframe的内容,但我知道由于同源策略 ,父网站无法操纵来自其他域的内容。

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. 我更喜欢一种方法,这意味着如果新网站需要包含iframe或现有网站改变了他们的样式,我就不必更改小部件。

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): 在托管窗口小部件的服务器上,您可以使用(如果使用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. 我建议在小部件所在的服务器上创建一个基于查询字符串参数返回CSS的Web服务。 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). 小部件iframe可以加载位于外部的资产,前提是它们在HTML中明确定义,而不是动态附加到DOM(考虑Google托管的JavaScript库,如jQuery和相关的CSS)。

Another solution, assuming you are using modern browser, you could use window.postMessage 另一种解决方案,假设您使用的是现代浏览器,则可以使用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. 此API允许您从父窗口向子窗口分派事件(以及与其一起的数据......例如CSS字符串)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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