【问题标题】:how to change logo within an iframe depending on top URL of the window如何根据窗口的顶部 URL 在 iframe 中更改徽标
【发布时间】:2015-11-12 00:20:31
【问题描述】:

我从早上开始就在尝试解决这个问题。我希望带有 iframe 的图像文件(徽标)根据某些 URL 进行更改。也就是说,当 iframe 嵌入到特定域中时,会出现内部徽标,而当 iframe 嵌入到域之外时,则会出现外部徽标。但我不断收到此错误 SecurityError: Blocked a frame with origin from access a frame with origin 协议、域和端口必须匹配。我不知道如何解决这个问题?有没有其他方法可以做到这一点?

这是我的代码

jQuery(document).ready(function($){
  var currentUrl = window.parent.location.hostname;
  if (currentUrl == 'www.mysite.com' || currentUrl == 'www.specific.com') {
    $(function() {
        $('img').remove('.logo-external');
    });
} else {
  $(function() {
        $('img').remove('.logo-internal');
    });
}
});

<div class="footer-right">
        <a class="logo" href="" target="_blank">
            <img class='logo-external' src="{{ ASSET_PATH }}logo-external.jpg" height="18" />
            <img class='logo-internal' src="{{ ASSET_PATH }}logo.png" height="18" />
        </a>
    </div>

【问题讨论】:

  • &lt;iframe src="foo.html?src=internal"&gt; 然后测试src 查询变量?
  • 我不确定我是否正确理解了您的答案。但我不想更改
  • 你不能使用window.parent,除非 iframe 和它的父级在同一个域中,或者the parent domain allows the child one to access it。这只有在您可以控制父服务器时才可行。 @MarcB 提供了一种解决方法,您可以使用它来标记任何内部请求,但这需要您拥有与其他客户端不同的 iframe URL。
  • 有没有替代window.parent的方法来达到这个效果?
  • 是的,看看我的答案并尝试一下。

标签: javascript iframe


【解决方案1】:

您不能使用window.parent,除非 iframe 和它的父级在同一个域中,或者如果 the parent domain allows the child one to access it。这只有在您可以控制父服务器时才可行。但是,有一个解决方法:

替换

var currentUrl = window.parent.location.hostname;

var temp = document.createElement("a");
temp.href = document.referrer;
var currentUrl = temp.hostname;

JS Fiddle demo using window.parent (not working)

JS Fiddle demo using document.referrer (does work)

【讨论】:

    猜你喜欢
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-17
    • 2010-12-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-31
    • 2021-12-20
    相关资源
    最近更新 更多