如何检测当前的iframe网址?

时间:2015-10-03 06:38:56

标签: javascript jquery html iframe

我写了一个html代码,用另一个网站初始化我的iframe。

我的域名是例如:

www.mydomain.com/Index.html

在这里有一个

 <iframe src = "www.anotherdomain.com/pages/firstPage.html"/>

每当iframe获得新的时,我想检测完整的新src网址。 iframe文本包含指向初始化页面中其他页面的链接。完成它是否可行且合法?谢谢。任何帮助表示赞赏。

我想这是跨越原始问题但是有解决方法吗?

更新

我试图通过

得到答案
 document.getElementById("myIframeId").src

在帧加载事件。但它一直显示初始化的src。它没有显示更新的src。

document.getElementById("myIframeId").contentWindow.location.href

给出安全错误,http帧正在尝试访问iframe中的https。协议不匹配。

我将localhost设置为SSL并使用了https,但请求被阻止了。我不知道为什么。

4 个答案:

答案 0 :(得分:2)

您可以检查某个时间间隔内的src属性,看看它是否已更改。这是一个能为你做到这一点的功能。

function watchIframeSRC(iframe, callback, interval) {
    // check every 1 second by default
    if (typeof interval === 'undefined') {
        interval = 1000;
    }
    var src = iframe.src;
    return setInterval(function () {
        // invoke the callback if the src is different
        if (iframe.src !== src) {
            src = iframe.src;
            callback(iframe);
        }
    }, interval);
}

var iframe = document.getElementById('test');

watchIframeSRC(iframe, function (iframe) {
    console.log("iframe src:", iframe.src);
});

答案 1 :(得分:1)

I don't agree with the answers which suggest that you should use "src" to detect the current url of the iframe. It simply doesn't give you the current url - but the url it started with.

The domain has to be from the same origin to use the method of the following code:

$(document).ready(function() {
  $('#myframe').load(function() {
    alert($(this).get(0).contentWindow.location.href);
  }); 
});

If the domains are from different origins - but you have access to both (or both are yours), then you can use window.postMessage function and contentWindow property of iFrame to send the data for the parent to show when a new page loads.

的功能

Here is a tutorial on that: http://javascript.info/tutorial/cross-window-messaging-with-postmessage

如果iFrame中的域是完全陌生的,我可以想到的一种方法是在服务器端脚本中加载该域并使其通过更改的链接呈现此数据。现在,您可以在iFrame中调用此脚本,并在加载时使用contentWindow.location.href属性。

答案 2 :(得分:0)

不,它不会抛出交叉原点错误。

<iframe id="test" src="www.anotherdomain.com/pages/firstPage.html"></iframe>

<强>使用Javascript:

alert(document.getElementById('test').src);

它会提示iframe的src值。

你也可以设置src。

document.getElementById('test').src = "http://www.neuralnetworksolutions.com/resources.php";

您可以从http://www.dyn-web.com/tutorials/iframes/

了解有关javascript iframe的更多信息

答案 3 :(得分:0)

确定。我一直在努力找出各种答案,但我能够在YQL和jQuery的帮助下做到这一点,以制作跨域ajax请求。 iFrame不允许我访问其内部事件。我用YQL从另一个域中删除了html并得到了工作。删除了我的iFrame并将已删除的html放入div中。

相关问题