>  기사  >  웹 프론트엔드  >  자바스크립트 크로스 도메인 방법_자바스크립트 기술 요약

자바스크립트 크로스 도메인 방법_자바스크립트 기술 요약

WBOY
WBOY원래의
2016-05-16 15:35:271443검색

이 글은 다른 프론트엔드 수강생의 글을 일부 인용하여 제가 작성한 내용을 실제적으로 요약한 것입니다.

다음 예에는 http://www.a.com/a.htmlhttp://www.a.com/c.html인 파일이 포함되어 있습니다. http://www.b.com/b.html, a.html에서 b.html의 데이터를 가져오기만 하면 됩니다

1.JSONP

jsonp는 src의 url 매개변수에 콜백 함수 이름을 추가하여 스크립트 태그에 도메인 간 제한이 없다는 점을 활용합니다. 그러면 서버는 콜백 함수 이름을 수신하고 데이터가 포함된 콜백 함수를 반환합니다.

  function doSomething(data) {
    // 对data处理
  }
  var script = document.createElement("script");
  script.src = "http://www.b.com/b.html?callback=doSomething";
  document.body.appendChild(script);

  // 1.生成一个script标签,将其append在body上,向服务器发出请求
  // 2.服务器根据 callback 这个参数生成一个包含数据的函数 doSomething({"a", "1"})
  // 3.页面事先已声明doSomething函数,此时执行 doSomething(data) 这个函数,获得数据

2.HTML5 게시물 메시지

704ef95ce250cc35ef75dcfff21bfd0b065276f04003e4622c4fe6b64f465b88 이 두 페이지에서 서로 소통해보세요

a.html

  window.onload = function() {
    window.addEventListener("message", function(e) {
      alert(e.data);
    });

    window.frames[0].postMessage("b data", "http://www.b.com/b.html");
  }

b.html

  window.onload = function() {
    window.addEventListener("message", function(e) {
      alert(e.data);
    });
    window.parent.postMessage("a data", "http://www.a.com/a.html");
  }

이렇게 페이지 a를 열면 a데이터가 먼저 나오고 그다음에 b데이터가 뜹니다

3.window.name iframe

window.name의 원칙은 동일한 창을 사용하여 서로 다른 페이지에서 window.name을 공유하는 것입니다. 이를 위해서는 a.html이 이후에 c.html을 얻을 수 있도록 a.com 아래에 c.html 프록시 파일을 생성해야 합니다. 동일한 출처.window.name

a.html

  var iframe = document.createElement("iframe");
  iframe.src = "http://www.b.com/b.html";
  document.body.appendChild(iframe); // 现在a.html里建一个引用b.html的iframe,获得b的数据

  var flag = true;
  iframe.onload = function() {
    if (flag) {
      iframe.src = "c.html"; 
// 判断是第一次载入的话,设置代理c.html使和a.html在同目录同源,这样才能在下面的else取到data
      flag = false;
    } else { // 第二次载入由于a和c同源,a可以直接获取c的window.name
      alert(iframe.contentWindow.name);

      iframe.contentWindow.close();
      document.body.removeChild(iframe);
      iframe.src = '';
      iframe = null;
    }
  }

b.html

window.name = "这是 b 页面的数据";

4.window.location.hash iframe

b.html은 c.html의 URL에 해시 값 형식으로 데이터를 추가합니다. c.html 페이지에서 location.hash를 통해 데이터를 얻은 다음 a.html로 전달합니다. a.html로 전달된 해시(물론 다른 곳에 업로드할 수도 있음)

a.html

  var iframe = document.createElement("iframe");
  iframe.src = "http://www.b.com/b.html";
  document.body.appendChild(iframe); // 在a页面引用b
  function check() { // 设置个定时器不断监控hash的变化,hash一变说明数据传过来了
    var hashs = window.location.hash;
    if (hashs) {
      clearInterval(time);
      alert(hashs.substring(1));
    }
  }
  var time = setInterval(check, 30);

b.html

  window.onload = function() {
    var data = "this is b's data"; 
    var iframe = document.createElement("iframe");
    iframe.src = "http://www.a.com/c.html#" + data;
    document.body.appendChild(iframe); // 将数据附加在c.html的hash上
  }

c.html

// 获取自身的hash再传到a.html的hash里,数据传输完毕
parent.parent.location.hash = self.location.hash.substring(1); 

5.CORS

CORS는 XMLHttpRequest 레벨 2에 지정된 도메인 간 방법입니다. 이 방법을 지원하는 브라우저에서는 서버가 Access-Control-Allow-Origin: *

을 설정해야 하는 한 javascript의 작성 방법은 도메인을 넘지 않는 ajax의 작성 방법과 정확히 동일합니다.

6.document.domain

이 방법은 http://www.a.comhttp://b.a.com
과 같이 기본 도메인은 동일하지만 하위 도메인이 다른 경우에 적합합니다. 이 두 도메인 이름 아래에 a.html과 b.html이 있으면

a.html

  document.domain = "a.com";
  var iframe = document.createElement("iframe");
  iframe.src = "http://b.a.com/b.html";
  document.body.appendChild(iframe);
  iframe.onload = function() {
    console.log(iframe.contentWindow....); // 在这里操作b.html里的元素数据
  }

b.html

  document.domain = "a.com";

참고: document.domain은 자체 도메인이나 상위 도메인으로 설정되어야 하며 기본 도메인은 동일해야 합니다.

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