利用在 iframe 改变后,window.name 仍然会保留,就可以获取到不同域中的数据。

    思路:

    • a 和 b 是同域的 http://localhost:3000
    • c 是独立的 http://localhost:4000
    • a 获取 c 的数据,a 先引用 c,c 把值放到 window.name
    • 然后立即把 a 引用的地址改到 b
    • 在 b 中就会保留这个 window.name

    代码

    1. <iframe src="http://localhost:4000/c.html"
    2. frameborder="0"
    3. onload="load()"
    4. id="iframe">
    5. </iframe>
    6. <script>
    7. let first = true;
    8. function load() {
    9. if (first) {
    10. let iframe = document.getElementById('iframe');
    11. iframe.src = 'http://localhost:3000/b.html';
    12. first = false;
    13. } else {
    14. console.log(iframe.contentWindow.name);
    15. }
    16. }
    17. </script>

    由于是在 load 中改变 src,那么需要进行判断,否则会进入死循环,因为改变 src 后又会进行加载。

    1. window.name = 'aa';

    在 c 中,只需要设置 window.name 即可。

    b 页面只是用于过渡,使得 a 页面可以直接通过 iframe.contentWindow.name 获取到数据