【问题标题】:How to get the current URL (not the src) of an iframe? [duplicate]如何获取 iframe 的当前 URL(不是 src)? [复制]
【发布时间】:2015-10-25 18:48:15
【问题描述】:

我的代码中有以下 iframe。

<iframe src="http://www.w3schools.com" id="myframe" name="myframe" height="100%" width="100%"></iframe>

我需要获取在 iframe 中进行一些导航后显示的页面的新 URL。

我尝试了几种方法,但都没有达到我想要的效果。一些方法返回与 src 相同的 URL。其他导致安全问题。

如何使用 AngularJS 完成这项工作?

(请朋友)

【问题讨论】:

    标签: javascript angularjs iframe


    【解决方案1】:

    正如你对我上一个答案的评论,这是我的new one form Marco Bonelli

    同源安全政策

    您无法使用 javascript 访问 &lt;iframe&gt;,如果您可以这样做,那将是一个巨大的安全漏洞。对于同源安全策略,任何浏览器都会阻止任何试图访问具有其他源的框架的脚本。

    例如,如果您在http://www.example.com 中并想使用src="http://www.anothersite.com" 访问一个,您将无法这样做,因为该框架有另一个来源。

    如果未维护以下变量中的至少一个,则认为来源不同:

    <protocol>://<hostname>:<port>/path/to/page.html
    

    如果您想访问框架,协议、主机名和端口必须与您的域相同。

    解决方法

    即使认为同源策略阻止脚本操作具有不同来源的站点的内容,如果您拥有两个域/站点,您可以使用 window.postMessage 及其相关事件 window.onmessage 在两个站点之间发送消息来解决此问题两页,像这样:

    在您的主页中

    var frame = document.getElementById('your-frame-id');
    
    frame.contentWindow.postMessage(/*any variable or object here*/, '*');
    
    In your <iframe> (contained in the main page):
    
    window.addEventListener('message', function(event) {
    
        // IMPORTANT: Check the origin of the data!
        if (~event.origin.indexOf('http://yoursite.com')) {
            // The data has been sent from your site
    
            // The data sent with postMessage is stored in event.data
            console.log(event.data);
        } else {
            // The data hasn't been sent from your site!
            // Be careful! Do not use it.
            return;
        }
    });
    

    【讨论】:

      【解决方案2】:

      将是没有 angularJS 的解决方案。 就是纯js。

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

      【讨论】:

      • 以上代码返回如下错误。阻止来源为“127.0.0.1:50129”的框架访问跨域框架。
      猜你喜欢
      • 2012-02-04
      • 2010-10-19
      • 2015-10-27
      • 2012-11-12
      • 2010-10-30
      • 2015-02-16
      相关资源
      最近更新 更多