假设我正在托管 site2.com
,并且有一个名为 site2.com/frame.html
的文件,它非常简单,如下所示:
<!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>
现在假设有一个名为
site1.com
的第三方网站希望通过iframe
元素嵌入此内容,代码如下:<!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>
当我在Chrome浏览器中打开
site1.com
时,我会得到这个结果(即site1.com
在此处充当第三方站点的角色,而site2.com
是托管要嵌入其他网站iframe内的内容的站点):
所以,框架内部的 body
元素的背景颜色设置为 site2.com/frame.html
中的样式为 yellowgreen
。当我试图用父网站 site1.com:3002
中指定的 blue
颜色覆盖它时,这不起作用。我甚至使用了带有 !important
属性的 id 选择器,但是这并没有传播到框架内容中。请注意,我能够为 iframe
元素本身(带红色边框)设置样式,但这不是我的问题所在。那么我该如何启用它呢?是否有某种标准方式,例如启用一些 http 策略或设置一些服务器头
site2.com
,告诉浏览器“请允许来自此来源的嵌入式框架上的 CSS 样式?”请注意,框架内容是跨域的。注:我通过使用 hosts 文件将
site1.com
和 site2.com
都指向 127.0.0.1 来设置此开发环境,并且我正在运行两个 node express 实例来模拟不同的服务器。