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

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

假设我正在托管 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 的第 3 方网站想要通过 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>

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

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

那么我该如何启用它呢?是否有一些标准的方法,比如启用一些 http 策略或设置一些服务器 headers site2.com 来告诉浏览器“请允许 CSS 在此来源的嵌入式框架上设置样式”?注意框架内容是cross-origin.

注意:这个开发环境是我设置的,用于练习使用hosts文件将site1.comsite2.com都指向127.0.0.1,我是运行两个node express实例模拟不同的服务器。

您不能设置第 3 方 iframe 的样式,因为它们受“Same-origin Policy”保护。

话虽如此,您可以尝试将样式表的 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>

并且 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);

您不能覆盖其他站点中的 iframe 样式!

这个脚本会做你想做的事

window.onload = function () {
    let myiFrame = document.getElementById("site2frame");
    let doc = myiFrame.contentDocument;
    doc.body.innerHTML =
      doc.body.innerHTML +
      "<style>body { background-color: blue;  !important} /* YOUR CSS*/</style>";
  };

这个例子摘自这篇文章:https://redstapler.co/how-to-apply-css-to-iframe/