使用JQuery获取Iframe的当前src

Mic*_*cah 17 iframe jquery

每当用户点击iframe中不是来自同一域的网页上的链接时,我都会收到通知.我知道xss限制,但我需要知道的是在iframe中提供的当前页面.有没有办法在不违反xss规则的情况下执行此操作?

小智 36

要使用jQuery获取iframe位置:

alert( $('iframeId').contents().get(0).location.href );
Run Code Online (Sandbox Code Playgroud)

  • 这仅适用于同一域的情况 - xss安全性会阻止它用于不同的域 (8认同)

jos*_*hls 9

如果不是跨站点脚本限制,这应该工作.不幸的是,我不知道如何在不违反这些限制的情况下获取URL.

<html>
    <head>
        <script type="text/javascript">
            function GetIFrameUrl()
            {
                alert('url = ' + document.frames['frame1'].location.href);
            }
        </script>
    </head>
    <body>
        <a href="#" onclick="GetIFrameUrl();">Find the iFrame URL</a>
        <iframe name="frame1" src="http://www.google.com" width="100%" height="400"></iframe>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

  • 是的,它确实.我不相信有办法在不违反规则的情况下做你需要的事情. (3认同)
  • 在firebug中的firefox中,我得到的是document.frames未定义 (2认同)

raa*_*m86 5

您可以使用 vanilla js 轻松完成。

  • 查询具有特定名称、ID、类或其他任何元素的文档
  • 获取该元素的属性来源

     //Get by Id
     var frame_src = document.getElementById('myIframe').src
     //Get by tag name - get the first
     var frame_src = document.getElementsByName('frmExternal')[0].src
     //Alert 
     alert(frame_src)
    
    Run Code Online (Sandbox Code Playgroud)