如何从iframe获取当前页面加载的URL

use*_*518 6 html javascript jquery

当我搜索并使用faroo移动到其他网页时,我正在使用iframe加载faroo.com作为默认src帧.但仍然在iframe src中显示faroo.com我只想捕获已加载到iframe的页面的url

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
    <script type="text/javascript">
    $(function(){
        $('#frameid').load(function(){
            var z=$('#frameid').attr('src');
            console.log('hi '+z);
        });

        $('#clicked').on('click', function(){
            $('#frameid').attr('src', 'http://www.faroo.com/');    
        });
    });

</script>

</head>
<body>

<iframe width="100%" height="500px" id="frameid" src="" name="iframe_a" ></iframe>

<p><input type="button" value="click me!" id="clicked"></p>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

console.log中的o/p始终是faroo.com而不是当前已加载的网站

Ale*_*dan 13

出于安全考虑,只要iframe的内容和引用的javascript托管在同一个域中,您就可以检索URL.

如果是这样的话,你可以这样做:

document.getElementById("frameid").contentWindow.location.href
Run Code Online (Sandbox Code Playgroud)

如果这两个域不同,那么您将拥有适用于跨站点引用脚本域的所有限制.例:

document.getElementById("frameid").src = 'http://www.google.com/';
alert(document.getElementById("frameid").documentWindow.location.href);

Error: Permission denied to get property Location.href
Run Code Online (Sandbox Code Playgroud)

当然(除非您在浏览器中发现一些巨大的安全漏洞),您无法javascript在父文档中实现所需的功能.让我们从一个简单的例子看看为什么.如果浏览器允许您需要,您可以轻松地:

  1. 使用隐藏的iframe创建页面(例如http://malicous.com/dont-trust)
  2. 在该iframe中,使用某个网站的登录过程打开子页面(例如http://insecure-web-site.com/redirectlogin)
  3. 如果存在儿童cookie,并且在某些情况下,框架内的页面将重定向到真实网站,继续用户登录.
  4. 现在,从父页面,您将能够读取URL中包含的登录过程中所有敏感信息,例如访问令牌,会话ID,...
  5. 此时,受害者网站及其用户面临着一系列新的安全威胁......