【问题标题】:How to detect the URL user is navigating to in an iframe from the outer window?如何从外部窗口检测用户在 iframe 中导航到的 URL?
【发布时间】:2014-08-02 16:32:32
【问题描述】:

场景如下:

该页面中有一个页面和一个 iframe。一开始,它们都来自同一个域(起源)。 iframe 可以包含到其他域的链接(或更改 window.location.href 的 javascript)。我想在外部框架中检测,当用户离开 iframe 中的原始域时,将外部页面的 window.location.href 替换为用户导航到的 URL,从而结束原来的 application在外框内运行。

尝试使用 beforeunload 事件,但内部框架的 location.href 没有改变。 iframe DOM 元素的 src 属性在 contentDocument 更改时也不会更改。

我的问题在当前的浏览器实现中是否可以解决,或者您会使用什么方法来获得最接近描述的行为?

【问题讨论】:

  • 并非如此。我在第一段中提到,当 iframe document.location.href 从内部更改时, src 属性不会更改。因此,'load' 事件和标记为答案的 contentDocument.location.href 没有解决方案,因为 iframe 导航到不同的域。
  • 您是否可以控制初始 iframe 应用程序?
  • 是的。我的脚本最初在外部框架和 iframe 中运行。

标签: javascript html dom iframe cross-domain


【解决方案1】:
    $(document).ready(function () {
                $("#widget").load(function () {
                    var ifr = document.getElementById("widget")
                    var anchors = ifr.contentDocument.getElementsByTagName("a");
                    for (var i in anchors) {
                        anchors[i].setAttribute("onClick", "testUrl()");
                    }
                });
            });  
function testUrl() {   
    //your code goes here for validating the URLs... 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-09
    • 2011-03-18
    • 2017-07-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 2018-01-18
    • 1970-01-01
    相关资源
    最近更新 更多