将 CSS 添加到 iFrame [重复]

Posted

技术标签:

【中文标题】将 CSS 添加到 iFrame [重复]【英文标题】:Add CSS to iFrame [duplicate] 【发布时间】:2011-10-21 02:01:18 【问题描述】:

可能重复:How to apply CSS to iFrame?

现在我正在通过 jquery 加载 iframe:

 $(window).load(function()
  $('iframe').load(function() 
      $('iframe').show()
      $('#loading').hide();

    );
    $('#loading').show();
    $('iframe').attr( "src", "http://www.url.com/");

  );

我有一个自定义样式表,我想将其应用于该页面。 iframe 中的页面不在同一个域中,这就是为什么它很棘手。我找到了允许您添加单个标签而不是整个样式表的解决方案。

编辑:相关页面是通过 Mobile Safari 中的 file:// 加载的,因此跨域策略不适用。

【问题讨论】:

你到底是怎么做到的?由于浏览器的跨域策略,它应该是不允许的。 您能为单个标签添加这些解决方案吗? @KARASZI 相反,这正是iframes 的用途。 @Jacek, ***.com/questions/217776/how-to-apply-css-to-iframe/… 我不明白为什么您不能从 iframe 加载样式表。我曾经和你一样为一个客户做过这个。我有一个 ajax 窗口加载,我从服务器端抓取数据,我只是将样式表动态嵌入到 iframe 中。 【参考方案1】:

基于解决方案你已经找到How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

或更多 jqueryish(来自Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
     rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" ));

至于安全问题:Disabling same-origin policy in Safari

【讨论】:

这应该让有安全意识的人头疼 非JQ方式报错,JQ方式无结果。错误是Cannot read property "document" of undefined. 那么跨域策略毕竟适用 @Jacek 啊,CDP 开始了吗?认为它会给我一个更具体的错误...... 试试***.com/questions/4556429/…

以上是关于将 CSS 添加到 iFrame [重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何将对象绑定到 iframe src

尝试使用 JavaScript 将 css 样式添加到 iframe

利用CSS注入(无iFrames)窃取CSRF令牌

如何让 IFrame 在 iOS Safari 中响应?

在 iframe 上自定义 css [重复]

需要使用 PHP 将变量添加到 Iframe URL [重复]