使用iframe+window.name跨域

2018年06月17日Web前端0

我们也可以使用iframe元素来协助我们实现前端跨域,不亲自试下的话,怎能算掌握呢?

自己使用iframe+window.name实现了下跨域。

假如我们是访问的server1(8080),需要跨域获取server2(9001)上的数据。

先看下server1下的index.html

var iframe = document.createElement('iframe'),
    firstIn = true;

iframe.style.display = 'none';

iframe.onload = function() {
    if (firstIn) {
        iframe.contentWindow.location = 'http://127.0.0.1:8080/proxy.html';
        firstIn = false;
    } else {
        var data = JSON.parse(iframe.contentWindow.name);
        console.log('get data: ', data);
        document.body.removeChild(this);
    }
};

iframe.src = 'http://127.0.0.1:9001';
document.body.appendChild(iframe);

首先设置了并加载了server2上的一个页面(暂且叫页面),再加载完成后,又重新设置了server1下的一个页面,其实是使用了name 值在不同的页面(甚至不同域名)加载后依旧存在的特点。(最多2MB)

server2下,返回name的值

var http = require('http');

http.createServer(function(req, res) {
    if ('/' === req.url) {
        res.end('<script> window.name = JSON.stringify({a:1}) </script>');
    }
}).listen(9001);

这样我们在server1下就可以拿到这个值啦。

目录