如何从iframe获取子URL?

时间:2018-02-11 09:56:14

标签: javascript html

这是我的iframe:

<iframe id="browsensearch" src="http://facebook.com/" width="100%" height="100%" allowtransparency="true" frameBorder="0">
    Your browser does not support IFRAME's
</iframe>

打开此网页时会获取网址facebook.com,但在此链接www.facebook.com/login.php上进行更改时,我希望获得子网址www.facebook.com

1 个答案:

答案 0 :(得分:0)

试试这个,等待2秒钟,然后观察控制台:

&#13;
&#13;
let iframe = document.getElementById('browsensearch');
iframe.onload = function() {
  let url = new URL(this.src);
  console.log(url.hostname);
};

//code below for testing
setTimeout(function() {
  iframe.src = 'https://www.baidu.com';
}, 2000);
setTimeout(function() {
  iframe.src = 'https://baidu.com';
}, 4000);
&#13;
<iframe id="browsensearch" src="https://baidu.com/" width="100%" height="100%" allowtransparency="true" frameBorder="0"></iframe>
&#13;
&#13;
&#13;