Web前端之路前端开发那些事技术干货

说说跨域那些事儿

2017-01-01  本文已影响111人  smartLife

首先纠正一个误区,跨域并非浏览器限制了发起跨站请求的这种能力,恰恰相反,我们可以发出请求,服务端也可以接收到请求并正常返回数据,只不过在返回之后浏览器会阻止非同源数据(response),从而在控制台打出一系列报错信息。

原文地址:说说跨域那些事儿,迁移到简书上来和大家共享

兼容性查找

文章中会涉及一系列兼容性的图解(mdn & can i use)和一些专有名词(mdn),可以通过两个渠道来查看

跨域类型

定义就不说了,从字面也可以看其含义,首先我们认识下哪些情况属于跨域,可以分为以下几点:

解决方案

document.domain

window.name

jsonp

/** 前端生成script标签,并将src中传入需要执行的callback **/
<script type="text/javascript">
    var ele = document.createElement('script');
    ele.type = "text/javascript"
    ele.src = "http://example.com?jsonp=cb";
    document.body.appendChild(ele);
</script>


/** 后端接到参数后给callback加入参数并执行 **/
<?php
    $cb = $_GET['cb'];
    $data = array('test1', 'test2', 'test3');
    echo $cb.'('.json_encode($data).')';
?>

postMessage

Storage.prototype.sendMessage_ = function(type, params, fn) {
    if (this.topWindow) {
        this.handleCookie_(type, params, fn);
        return;
    }
    var eventId = this.addToQueue_(fn, type);
    var storageIframe = document.getElementById('mip-storage-iframe');
    var element = document.createElement("a");
    element.href = this.origin;
    var origin = element.href.slice(0, element.href.indexOf(element.pathname) + 1);     

    storageIframe.contentWindow.postMessage({
        type: type,
        params: params,
        eventId: eventId
    }, origin);
}

Storage.prototype.bindEvent_ = function() {
    window.onmessage = function (res) {
        // 判断消息来源           
        if (window == res.source.window.parent &&
            res.data.type === this.messageType.RES &&
            window.location.href.match(res.origin.host).length > 0) {               
            var fn = this.eventQueue[res.data.eventId];
            fn && fn();
            delete this.eventQueue[res.data.eventId];
            // reset id
            var isEmpty = true;
            for (var t in this.eventQueue) {
                isEmpty = false;
            }
            if (isEmpty) {                  
                this.id = 0;
            }
        }                   
    }.bind(this);
}

cors

上一篇 下一篇

猜你喜欢

热点阅读