使用JQuery获取Iframe的当前src

使用JQuery获取Iframe的当前src,jquery,iframe,Jquery,Iframe,每当用户单击iframe中不来自同一域的页面上的链接时,我都需要得到通知。我知道xss的限制,但是我只需要知道Iframe中提供的当前页面。有没有一种方法可以在不违反xss规则的情况下执行此操作?如果没有跨站点脚本限制,则应该可以。不幸的是,我不知道如何在不违反这些限制的情况下获取URL <html> <head> <script type="text/javascript"> function GetIFram

每当用户单击iframe中不来自同一域的页面上的链接时,我都需要得到通知。我知道xss的限制,但是我只需要知道Iframe中提供的当前页面。有没有一种方法可以在不违反xss规则的情况下执行此操作?

如果没有跨站点脚本限制,则应该可以。不幸的是,我不知道如何在不违反这些限制的情况下获取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>

函数GetIFrameUrl()
{
警报('url='+document.frames['frame1'].location.href);
}

使用jQuery获取iframe位置:

alert( $('iframeId').contents().get(0).location.href );

你可以很容易地做到这一点与香草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)
    
//如果窗口在iframe中打开,则重定向到主站点
if(window.top.location!=window.self.location)
{
警报(窗口、自身、位置);
//top.window.location.href=window.self.location;
}

是的,是的。我不相信有什么方法可以在不违反规则的情况下完成您需要的操作。在firebug中的firefox中,我得到的只是document.frames未定义这是一个很好的答案,但询问者要求的是一个jQuery解决方案,而不是普通的JavaScript。@LS:是的,但合理的问题应该理解为“使用jQuery执行此操作的最佳实践方法?”。。。如果这意味着使用普通JS就可以了,那么这对methis不起作用这只在同一个域中起作用——xss安全性防止它对不同的域起作用注意,如果JS在iframe中运行,那么像这样选择iframe将不起作用,但像“$('iframe',window.parent.document)”这样选择它会起作用。(仍假定为相同的域。)
  <script type="text/javascript"> // if window open in iframe then redirect to main site
         if(window.top.location != window.self.location)
         {
            alert(window.self.location);
            // top.window.location.href = window.self.location;
         }
    </script>