[TOC]

跨域方式

document.domain + iframe

子域上的 window:document.domain

一、根据定义,两个具有不同域的 URL 具有不同的源。
1、但是,如果窗口的二级域相同,例如 john.site.com,peter.site.com 和 site.com(它们共同的二级域是 site.com),我们可以使浏览器忽略该差异,使得它们可以被作为“同源”的来对待,以便进行跨窗口通信。
2、为了做到这一点,每个这样的窗口都应该执行下面这行代码,它们可以无限制地进行交互了

document.domain = 'site.com';

| 【示例】```javascript

helloa <iframe src=”http://b.test.com/b.html“ frameborder=”0” onload=”load()” id=”frame”

```javascript
<body>
  hellob
  <script>
    document.domain = "test.com";
    var a = 100;
  </script>
</body>

| | —- |

限制

一、该方式只能用于二级域名相同的情况下。

window.location.hash + Iframe

实现原理

一、原理就是通过url带hash,通过一个非跨域的中间页面来传递数据

实现流程

一、a给c传一个hash值,c收到hash值后,把hash值传递给b,最后b将结果放到a的hash值中。
1、a 、b同域:http://localhost:8000
2、c:http://localhost:8080

| 【示例】```javascript

```javascript
<script>
  window.parent.parent.location.hash = location.hash;
</script>
<body></body>
<script>
  console.log(location.hash);
  const iframe = document.createElement("iframe");
  iframe.src = "http://localhost:8000/hash/b.html#name2";
  document.body.appendChild(iframe);
</script>

| | —- |

window.name + Iframe

原理

1、当window的location变化,然后重新加载,它的name属性可以依然保持不变
2、通过iframe的src属性由外域转向本地域,跨域数据即由iframe的window.name从外域传递到本地域。

| 【示例】a、b同于:http://lcoalhost:8000,c:http://localhost:8080```javascript

<iframe src=”http://localhost:8080/name/c.html“ frameborder=”0” onload=”load()” id=”iframe”

b.html为中间代理页,与a.html同域,内容为空```javascript
<div></div>
<script>
  window.name = "aSuncat-20220506:这是window的name";
</script>

| | —- |

防御措施

一、可以在 http 返回头 添加X-Frame-Options: SAMEORIGIN 防止被别人添加至 iframe