>  기사  >  웹 프론트엔드  >  Javascript 크로스 도메인 문제에 대한 심층 분석_javascript 기술

Javascript 크로스 도메인 문제에 대한 심층 분석_javascript 기술

WBOY
WBOY원래의
2016-05-16 16:03:261112검색

크로스도메인이란 무엇인가요?

a.com/get.html이 b.com/data.html에서 데이터를 가져와야 하고 a.com과 b.com이 동일한 서버가 아니라고 가정합니다. 이는 Javascript를 포함하는 교차 도메인 교차 도메인입니다. 동일 출처 정책은 간단히 말해서 웹 사이트의 보안을 보호하고 외부 도메인(동일 출처가 아닌) 서버의 js에 의해 웹 사이트의 콘텐츠가 수정되는 것을 방지하는 것입니다.
교차 원인을 일으키는 조건이 무엇인지 확인하려면 표를 인용하세요.

하지만 때로는 꼭 필요한 경우가 있는데 어떤 방법이 있나요?

1. JsonP

크로스 도메인에 관해서라면 먼저 jsonp를 언급하지 않을 수 없습니다. jsonp는 실제로 JavacScript Object Notation with Padding의 약어로, 콘텐츠가 채워진 json 형식의 데이터로 이해될 수 있습니다.
위에서 콜백을 선언하고 외부 도메인 b.com의 data.js를 호출하고, data.js를 호출하기 때문입니다.
콜백({msg:"tqtan"});
이런 식으로 외부 도메인을 참조하는 js를 호출하면 로컬 콜백()이 호출되어 데이터 전송이 이루어집니다.
위의 내용은 단순한 크로스 도메인이므로 jQuery의 실제 적용 사례를 살펴보겠습니다.

jQuery의 Ajax는 두 가지 방법을 통해 외부 도메인에서 데이터를 가져올 수 있습니다.

1.$.getJSON()

이 방법은 외부 도메인에서 Json을 요청하는 간단하고 투박한 방법입니다.

코드 복사 코드는 다음과 같습니다.

$.getJSON("http://b.com/dataServlet?callback=?",function(data){
console.log(data.msg);
});

위 요청이 b.com 아래의 서블릿 페이지에 액세스하고 전달된 매개 변수가 callback=?이라고 가정하면 jQuery는 자리 표시자?를 채울 문자열을 자동으로 생성합니다(예: callback=jQuery17207481773362960666_1332575486681). 이는 서버에 대한 고유 식별자를 선언합니다. 서버는 이 콜백 값을 사용하여 json 형식 데이터만 반환하면 됩니다. 예:

코드 복사 코드는 다음과 같습니다.

//dataServlet.java
문자열 콜백 = req.getParameter("callback");
PrintWriter 출력 = resp.getWriter();
out.print(콜백 "('msg','tqtan')");

이런 방식으로 동일하지 않은 원본 서버에서 데이터를 성공적으로 가져올 수 있습니다.

2.$.ajax()

더 많은 링크를 맞춤 설정할 수 있다는 점을 제외하면 구현 원칙은 위와 동일합니다.

$.ajax({
url:'http://b.com/dataServlet?words=hi',
dataType:'jsonp',
jsonp : 'jsoncallback',
jsoncallback : 'tqtan',
success:function(data){
console.log(data.msg);
},
error: function (e) {
console.log(e);
}
});

콜백 이름은 사용자 정의할 수 있습니다. 여기서는 'tqtan'으로 변경되며, word=hi 값을 여기에 전달할 수 있습니다.
JsonP 형식은 GET 형식으로만 서버에 요청할 수 있습니다.

2. 문서.도메인

이 방법은 기본 도메인은 동일하지만 하위 도메인이 다른 교차 도메인에만 적용됩니다.
이것이 바로 get.a.com과 data.a.com 간의 도메인 간 문제입니다. 해결 방법은 매우 간단합니다.
get.a.com/get.html이 data.a.com/data.html의 데이터를 가져와야 하는 경우 먼저 get.html에 iframe을 삽입하고 src는 data.a.com/data.html을 가리킨 다음 data.html에서 data.html의 내용을 제어하려면 document.domain='a.com';을 작성하세요.

//get.html
var iframe = document.creatElement("iframe");
iframe.src="http://data.a.com/data.html";
iframe.style.display="none";
document.body.appendChild(iframe);
document.domain = 'a.com';
iframe.onload = function(){
var otherDocument = iframe.contentDocument || iframe.contentWindow.document;
//otherDocument就是另一个页面的document
//do whatever you want..
};
//data.html
document.domain = 'a.com';

3. URL 해시

URL 해시를 통해 도메인 간을 달성할 수도 있습니다. 해시는 http://targetkiller.net/index.html#data와 같이 url# 뒤의 콘텐츠입니다. 여기서 #data는 해시입니다. 크로스 도메인을 달성하기 위해 이것을 어떻게 사용합니까?

여전히 같은 예입니다. a.com/get.html은 b.com/data.html을 가져와야 합니다. 먼저 get.html에서 iframe을 생성하고 src는 여전히 data.html을 가리킨 다음 해시 값을 매개변수를 전달합니다. 반대편의 Data.html은 획득한 해시를 기반으로 응답하고 iframe 자체를 생성하며 src는 a.com/proxy.html을 가리키고 응답 데이터를 해시에 추가합니다. 그 후에는 a.com/proxy.html은 동일한 a.com 상위 도메인에 있는 get.html의 해시만 수정하면 됩니다. 마지막으로 데이터를 얻는 방법은 무엇입니까? get.html에 타이머 setInterval을 작성하고 정기적으로 새 해시가 있는지 모니터링하기만 하면 됩니다.

이것을 보면 혼란스러울 수 있습니다. 다음은 몇 가지 질문입니다.

1.proxy.html의 역할은 무엇인가요?
get.html과 data.html이 동일한 도메인에 있지 않기 때문에 location.hash 값을 수정할 수 없으므로, Proxy.html을 사용하여 먼저 프록시를 찾는 페이지로 이동한 다음 parent.location.hash를 사용하세요. 즉, 아들(get.html)도 응답을 받을 수 있도록 아버지를 수정합니다.
a.com/get.html

var iframe = document.createElement('iframe');
iframe.src = 'http://a.com/get.html#data';
iframe.style.display = 'none';
document.body.appendChild(iframe);
//周期检测hash更新
function getHash() {
var data = location.hash ? location.hash.substring(1) : '';
console.log(data);
}
var hashInt = setInterval(function(){getHash()}, 1000);
a.com/proxy.html
parent.location.hash = self.location.hash.substring(1);
b.com/data.html
//模拟一个简单的参数处理操作
if(location.hash){
var data = location.hash;
doSth(data);
}
function doSth(data){
console.log("from a.com:"+data);
var msg = "hello i am b.com";
var iframe = document.createElement('iframe');
iframe.src = "http://a.com/proxy.html#"+msg;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}

4、window.name

这种方法比较巧妙,引用圆心的解释,name 值在不同的页面(甚至不同域名)加载后依旧存在,并且可以支持非常长的 name 值(2MB)。
具体例子依旧如上,同时也是需要一个代理页面。
a.com/get.html请求b.com/data.html,首先get.html创建一个iframe,src指向data.html,然后监听iframe的onload事件。与此同时,在data.html设置window.name = data;把window.name赋值。然后onload事件后马上把iframe的跳到本地a.com/proxy.html。因此window.name就共享到了src为proxy.html的找个iframe中,接下来,就是同源间获取值的事了。
a.com/get.html

var state = 0,
iframe = document.createElement('iframe'),
iframe.src = 'http://b.com/data.html";
iframe.style.display = 'none';
loadfn = function() {
if (state === 1) {
var data = iframe.contentWindow.name;
console.log(data);
} else if (state === 0) {
state = 1;
//跳到proxy.html
iframe.contentWindow.location = "http://a.com/proxy.html";
}
};
if (iframe.attachEvent) {
iframe.attachEvent('onload', loadfn);
} else {
iframe.onload = loadfn;
}
document.body.appendChild(iframe);
a.com/proxy.html
// proxy.html的操作主要是删除get.html的iframe,避免安全问题发生
iframe.contentWindow.document.write('');
iframe.contentWindow.close();
document.body.removeChild(iframe);
b.com/data.html
var data = "hello,tqtan";
window.name = data;

5、 postMessage()

html5的新方法postMessage()优雅地解决了跨域,也十分容易理解。
发送方调用postMessage()内容,接受方监听onmessage接受内容即可。
假设发送方为a.com/send.html,接受方为b.com/receive.html。
a.com/send.html

var iframe = document.createElement("iframe");
iframe.src = "http://b.com/receive.html";
document.body.appendChild(iframe);
iframe.contentWindow.postMessage("hello","http://b.com");
b.com/receive.html
window.addEventListener('message', function(event){
// 通过origin属性判断消息来源地址
if (event.origin == 'http://a.com') {
console.log(event.data);
console.log(event.source);//发送源的window值
}
}, false);

6、CORS(后台实现)

以上5点都是前端实现的跨域,但是后台参与会让跨域更容易解决,也就是用CORS。
CORS是Cross-Origin Resource Sharing的简称,也就是跨域资源共享。它有多牛逼?之前说JsonP只能get请求,但CORS则可以接受所有类型的http请求,然而CORS只有现代浏览器才支持。
怎样使用?前端只需要发普通ajax请求,注意检测CORS的支持度。引用自蒋宇捷。

function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// 此时即支持CORS的情况
// 检查XMLHttpRequest对象是否有“withCredentials”属性
// “withCredentials”仅存在于XMLHTTPRequest2对象里
xhr.open(method, url, true);
}
else if (typeof!= "undefined") {
// 否则检查是否支持XDomainRequest,IE8和IE9支持
// XDomainRequest仅存在于IE中,是IE用于支持CORS请求的方式
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// 否则,浏览器不支持CORS
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}

与此同时,服务器端只需要设置Access-Control-Allow-Origin头即可。

java中你只需要设置

复制代码 代码如下:

response.setHeader("Access-Control-Allow-Origin", "*");

为了安全,也可以将*改为特定域名,例如a.com。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.