Way cross-domain JavaScript summary

1. jsonp request

Jsonp principle is to use cross-domain script tag properties, unrestricted load resources from other domains, there is a similar tag img.

Cons: only supports GET requests without the support of other types of HTTP POST requests.

<script>
    //回调函数,用来发送给 php服务器
    function getData(data) {
        console.log(data);
    }

    //核心本质   就是后端服务器  返回一个函数调用   getData('js')
    createJsonp();
    
    function createJsonp() {
        const s = document.createElement('script');
        s.src='http://localhost/data.php?callback=getData';
        document.body.appendChild(s);
    }
</script>
<?php
//跨域必须允许,后台说了管用
//header('Access-Control-Allow-Origin:*');
$receive=$_GET["callback"];  // 拿到回调函数,可以用来判断
$arr = [
    [
        'id'=>1,
        'name'=>'追梦',
        'age'=>18
    ],
    [
       'id'=>2,
       'name'=>'阿飞',
       'age'=>18
    ]
];

//编译成字符串
echo json_encode($arr);
?>

2. document.domain

This method is used in various primary domain in the same sub-domain cross-domain access. For example: http://a.frame.com and http://b.frame.com their main domain name is frame.com both domain names in the file can be accessed in this way, by two a specific file setting field document.domain = "frame.com" can achieve the purpose of cross-domain access.

Practical applications are often used in the iframe window between the access policy in accordance with the homologous browser, the browser can not interoperate js of different domains between the frame, the window is not a window to get another properties and methods of contentWindow object (note contentWindow object is to get only the properties and methods are not available).

In order to get the data, as long as the writing after document.domain = "main domain", respectively, in two iframe, arranged such, you can get the object properties and methods of contentWindow.

3. window.name

The window has a name attribute characteristics: in one window (window) of the life cycle, the window to load all the pages are sharing a window.name each page of window.name have read and write permissions, window .name is the persistence of a window in a load off all pages, and new pages will not load and reset.

For example, I set up a window.name = "a" in a.html this page; then let the window b.html reload the page, and then output in b.html page window.name will find window.name = "a". So even if a.html b.html two pages and not in, you can also get a set of pages in the same domain as the page b window.name value, cross-domain core idea is this principle.

Examples: getDomainData.html page data is acquired, null.html is a blank page and getDomainData.html same domain, its role as a relay station, the data transition. data.html is the page where you want to get the data, with the data we want here, and it getDomainData.html in different domains, so take a cross-domain data access.

Specific process is as follows: the establishment of a sub-page in getDomainData.html the iframe, the iframe src to this point b.com/data.html, such as after the iframe has finished loading can be accessed data.html the window. name of the data, and then after the iframe src changed a.com/null.html, jump back to the same domain getDomainData.html, so according to the same origin policy, getDomainData.html can access the data acquired to null.html .html of the data. After obtaining this data is best destroyed iframe, freed memory, but also to ensure safety.

getDomainData.html:

<script type="text/javascript">
     var flag=0;
     var data;
     var iframe=document.createElement("iframe");//创建一个中转站iframe
     document.appendChild(iframe);
    
     getData=function(){ //iframe加载完成后调用的处理函数
         if(flag==1){
             data=iframe.contentWindow.name;   //读取b.html中的window.name
         }else{
             flag=1;
             iframe.src="http://a.com/null.html";//跳回getDomainData.html的同一个域
         }
     };
    
     iframe.src="http://b.com/data.html";//设置src到要获得数据的域中的对应页面

    if (iframe.attachEvent) { //兼容IE,监听iframe加载完成
        iframe.attachEvent('onload', getData);
    } else {
        iframe.addEventListener('load',getData);
    }
</script>

data.html:

<script>
window.name="被获取数据"//简单的一行代码
</script>

Last iframe destruction:

<script>
    iframe.contentWindow.document.write("");     //情况iframe中的内容
    iframe.contentWindow.close();               //避免iframe的内存泄漏
    document.body.removeChild(iframe);          //移除iframe节点
</script>

4. window.postMessage

window.postMessage is a new way to implement cross-domain access html5, can use it to send messages to other objects in the window, regardless of whether the homologous or window object belonging to different sources.

5. HEARTS

Use custom HTTP headers allow the browser to communicate with the server to determine the success of the request or response should or should fail.

6. Web Sockets

After js created a web socket, there will be a HTTP request is sent to the browser to initiate a connection. After obtaining the server response, connections can be made using HTTP upgrade from HTTP protocol to exchange web socket protocol.

For details, see Gangster summary: https://segmentfault.com/a/1190000008525104

Guess you like

Origin www.cnblogs.com/danew/p/11421125.html