跨域

134 阅读1分钟
  1. location.hash + iframe 跨域 iframe中的src指向页面地址,有同域跟跨域之分。同域或跨域主页面跟iframe页面之间的通信方式也不相同。

    • 同域时,父页面可以通过iframe.contentWindow, 获取iframe的window对象;iframe.contentDocument, 获取iframe的document对象。子页面也可以通过以下这几个api操作父页面的内容
window.parent 获取上一级的window对象,如果还是iframe则是该iframe的window对象
window.top 获取最顶级容器的window对象,即,就是你打开页面的文档
window.self 返回自身window的引用。可以理解 window===window.self
window.parent.document.XX

window.parent.function
  • 跨域时,由于iframe和父页面处在不同域下,拿不到父页面的大多数属性与方法。可以通过设置一个代理页面(代理页面与父页面同域)进行通信。
  1. window.name + iframe window 对象的 name 属性是一个很特别的属性,当该 window 的 location 变化,然后重新加载,它的 name 属性可以依然保持不变。 a 和 b 是同源的,c 是独立的. a 先引用c,c把值放到window.name中,然后把a引用的地址改到b
a.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>a.html</title>
</head>
<body>
    <iframe id="iframe" src="http://localhost:4000/c.html" frameborder="0" "load()"></iframe>
    <script type="text/javascript">
        let first = true;//第一次加载
        function load(){
          if(first){
              let iframe = document.querySelector("#iframe");
              iframe.src = 'http://localhost:3000/b.html';
              first = false;
          }else{
              console.log(iframe.contentWindow.name);//yuhua
          }
     }
 </script>
</body>
</html>

b.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
 <title>Document</title>
</head>
<body>

</body>
</html>
  
  c.html
  <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    c页面
    <script type="text/javascript">
        window.name = 'yuhua';
    </script>
</body>
</html>