[转] 跨域

同源策略

特别注意两点:

第一,如果是协议和端口造成的跨域问题“前台”是无能为力的

第二:在跨域问题上,域仅仅是通过“URL的首部”来识别而不会去尝试判断相同的ip地址对应着两个域或两个域是否在同一个ip上。

“URL的首部”指window.location.protocol +window.location.host,也可以理解为“Domains, protocols and ports must match”。

CROS跨域

function CreateCROSRequest (method,url) {
    var xhr = new XMLHttpRequest();
    if ('withCredentials' in xhr) {
        xhr.open(method,url,true);
    }//chrome
    else if(typeof XDomainRequest!= 'undefined'){
    var xhr = new XDomainRequest();
        xhr.open(method,url,true);
    }//IE
    else{
        xhr = null;
    }
    return xhr;
}
var request = CreateCROSRequest("GET","http://www.baidu.com");
if (request) {
    request.onload = function () {
        console.log('success')
    }
    request.send();
}

JSONP跨域

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div class="container">

    </div>
</body>
<script>
//回调函数
function handleResponse(response){
    document.getElementById("container").innerHTML=response;
}
var script = document.createElement('script');
script.src = 'http://www.baidu.com/json/?callback=handleResponse';
document.body.insertBefore(script, document.body.firstChild);
</script>
</html>

HTML5 window.postMessage

// 主页面 
<script>
function onLoad() {
  var iframe =document.getElementById('iframe');
  var iframeWindow = iframe.contentWindow;
  iframeWindow.postMessage("I'm message from main page.");
}
</script>
<iframe src="http://www.test/b.html" onload="onLoad()"</iframe>    

// b 页面
<script>
window.onmessage = function(e) {
  e = e || event;
  console.log(e.data);
}
</script>
posted @ 2018-01-26 15:29  {前端开发}  阅读(265)  评论(0编辑  收藏  举报