让第 3 方更改我网站 iframe 的样式

mls*_*lst 8 html javascript css iframe http

假设我正在托管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>
Run Code Online (Sandbox Code Playgroud)

现在说 3rd 方网站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>
Run Code Online (Sandbox Code Playgroud)

所以当我打开时,我在 Chrome 浏览器中得到了这个结果site1.com(即site1.com在这里扮演 3rd 方站点的角色,而site2.com托管内容的站点则嵌入到其他网站的 iframe 中):

在此处输入图片说明

所以body框架内元素的背景是yellowgreensite2.com/frame.html. 当我尝试使用blue父网站中指定的颜色覆盖它时,site1.com:3002这不适用。我什至使用了带有!important属性的id 选择器,但这不会传播到框架内容内部。请注意,我可以设置iframe元素本身的样式(带有红色边框),但这不是我的问题。

那么我怎样才能启用它呢?有没有一些标准的方法,比如启用一些 http 策略或设置一些服务器标头site2.com,告诉浏览器“请允许来自这个来源的嵌入框架的 CSS 样式”?请注意,框架内容是跨域的。

注:此开发环境是由我通过使用主机文件指向这两个练习设置site1.comsite2.com为127.0.0.1,我运行两个节点Express实例来模拟不同的服务器。

Spe*_*ric 8

您不能设置第 3 方 iframe 的样式,因为它们受“同源策略”保护。

话虽如此,您可以尝试将样式表的 URL 作为 GET 参数发送,并site2.com/frame.html读取此参数并将其动态添加到其<head>.

例如,site1.com可以像这样创建 iframe:

<iframe id="site2frame"
  title="Inline Frame Example"
  width="300"
  height="200"
  src="https://site2.com:3002/frame.html?css=externalstylesheet.css">
</iframe>
Run Code Online (Sandbox Code Playgroud)

并且site2.com/frame.html可以读取 GET 参数,创建一个设置为参数值的link属性href并将其附加到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);
Run Code Online (Sandbox Code Playgroud)

编辑 pedantic-euclid-m120j

  • 这是要走的路。但为了保持“site2.com”的安全,您还应该考虑使用强大的内容安全策略(以 HTTP 标头或 &lt;meta&gt; 标记的形式):https://developer.mozilla.org/en-美国/文档/Web/HTTP/CSP (2认同)