【问题标题】:Let 3rd party change styles of an iframe of my site让第 3 方更改我网站 iframe 的样式
【发布时间】:2021-09-23 00:12:47
【问题描述】:

假设我托管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中的样式设置。当我尝试用父网站site1.com:3002 中指定的blue 颜色覆盖它时,这不适用。我什至使用了带有!important 属性的id 选择器,但这并没有传播到框架内容的内部。请注意,我可以设置 iframe 元素本身的样式(带有红色边框),但这不是我的问题。

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

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

【问题讨论】:

标签: javascript html css http iframe


【解决方案1】:

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

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

例如,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);

【讨论】:

【解决方案2】:

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

【讨论】:

    【解决方案3】:

    这个脚本会做你想做的事

    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/

    【讨论】:

      猜你喜欢
      • 2018-11-10
      • 2014-06-12
      • 1970-01-01
      • 2011-02-23
      • 2013-05-04
      • 1970-01-01
      • 2011-11-30
      相关资源
      最近更新 更多