Analysis of cross-domain communication/cross-domain upload

Source: Internet
Author: User
Tags button type domain server in domain to domain

Web project cross-domain issues mainly include cross-domain communication and cross-domain upload, the following two aspects of the analysis, the specific project to use which plan to see the specific needs of the project.

Cross-domain communication
    • Jsonp
    • Hash
    • Server Proxy
    • Window.name
    • Cors
    • PostMessage
    • redirect
Jsonp

Principle: Initiate a GET request, the callback function takes to the request parameter, sends the data past

Cons: The server needs to support Jsoncallback parameters

Benefits: The industry's more general-purpose scenarios, including operations such as RBI, can be used with similar techniques

Browser support: chrome/firefox/safari/opera/ie6+

Client

//jquery$(function(){    $.ajax({        url: ‘http://bbb.com:8888/crossdomain/jsonp.php‘,        dataType: ‘jsonp‘,        jsonp : ‘callback‘, //指定callback参数名        data: {name: ‘ysj‘} //数据    }).done(function(result){        alert(result) // {code:200}    })})//实际请求:http://bbb.com:8888/crossdomain/jsonp.php?callback=jQuery111108173922670539469_1410615060808&name=ysj&_=1410615060809  //native jsvar temp = document.createElement(‘script‘);temp.src = ‘http://bbb.com:8888/crossdomain/jsonp.php‘      + ‘?callback=jsonpCallback&name=ysj‘; //设置callback参数document.body.appendChild(temp)temp.parentNode.removeChild(temp);function jsonpCallback(result) {    alert(result) // {code:200}}

Server

$callback = $_GET[‘callback‘];echo $callback . "({code:200})";
Hash

Principle: The parent page sets the parameter setting to the child IFRAME hash, the sub-iframe listens for the hash change, the response data is set to the parent page hash

Disadvantage: Need server support, hash is often used for routing, not suitable for communication

Benefits: None

Browser support: chrome/firefox/safari/opera/ie6+

Code slightly

Server Proxy:

Principle: A domain request B domain, set a Proxy Server script page in domain A, accept the parameter of a, take the content of B domain by initiating an HTTP request, and then return to domain A

Cons: You need to add a proxy page to a domain server

Benefits: A more general scenario

Browser support: chrome/firefox/safari/opera/ie6+

Code slightly

Window.name

Principle: A domain request B domain of the page, b after loading the response data to Window.name, and then redirect to a page, at this time window.name did not change

Cons: Domain B needs to be redirected to a processing page in domain A

Benefits: None

Browser support: chrome/firefox/safari/opera/ie6+

Code slightly

Cors (cross-domain resource sharing):

Principle: Server Settings Accessibility access-control-allow-origin: *, browser AJAX fetch data

Cons: Requires server special handling

Benefits: A better future

Browser support: chrome/firefox/safari/opera/ie10+

Code slightly

PostMessage

Principle: Use HTML5 's PostMessage API to cross-domain wear data

Cons: Compatibility

Benefits: A better future

Browser support: chrome/firefox/safari/opera/ie10+

The code is shown in the following cross-domain upload

redirect

Principle: A domain iframe request b field, take the URL, b field take response, return to the handler page of domain A

Disadvantages: There are security risks

Benefits: Simple and browser-supported solutions

Browser support: chrome/firefox/safari/opera/ie6+

The code is shown in the following cross-domain upload

Cross-Domain uploads
    • Cors
    • redirect
    • PostMessage
Cors

Principle: Using Xmlhttprequest2+formdata, server settings access-control-allow-origin: *, cross-domain resource access this feature, plus HTML5 FormData can send file features.

Cons: Requires server settings to support cross-domain access access-control-allow-origin: *

Benefits: A better future

Browser support: chrome/firefox/safari/opera/ie10+

Client

document.forms[0].onsubmit = function() {    var xhr = new XMLHttpRequest();    var data = new FormData(document.forms[0]);    xhr.open(‘POST‘ , this.action)    xhr.onload = function(){        console.log(xhr.responseText)    }    xhr.send(data)    return false}

Server

header("Access-Control-Allow-Origin: *");echo "{code:200}";
redirect

Principle: A domain form is submitted to the B field, A's form target points to a domain's iframe,b domain redirect to the result page of domain A, bringing the data. Requires the browser to send a redirect parameter, the server checks to have this parameter, then redirects to the results page, the content to the above parameters

Cons: Server and client special parameter redirect processing

Benefits: Supports all browsers

Browser support: chrome/firefox/safari/opera/ie6+

Client

<form method="post" action="http://bbb.bbb.com:8888/crossdomain/redirect.php" target="_iframe"><input type="hidden" name="redirect" id="redirect"> <input type="file" name="Filedata"><button type="submit">submit</button></form><iframe id="_iframe" name="_iframe"></iframe>document.forms[0].onsubmit = function() {    document.getElementById(‘redirect‘).value = window.location.href.replace(/\/[^\/]*$/,‘/result.html?%s‘); //设置redirect参数值    var iframe = document.getElementById(‘_iframe‘)    iframe.onload = function(){        console.log(iframe.contentDocument             ? iframe.contentDocument.body.innerHTML             : iframe.document.body.innerHTML) // {code:200}    }}

redirect page

document.body.innerText=document.body.textContent=decodeURIComponent(window.location.search.slice(1)); //把参数中的数据写入文档

Server

$redirect = isset($_REQUEST[‘redirect‘]) ?            stripslashes($_REQUEST[‘redirect‘]) : null;$json = ‘{code:200}‘;//有redirect参数,则重定向。需要注意的是服务器需要设置一个白名单,符合的才给予重定向,否则有安全问题if ($redirect) {    //页面重定向,把返回数据替换掉redirect url中的%s    header(‘Location: ‘.sprintf($redirect, rawurlencode($json))); }
PostMessage

Principle: A domain ready parameters sent to the Postmessageapi page of Domain B via postmessage, this page submits the data in xhr+formdata way to the URL of a domain request, Postmessageapi then postmesage the returned data to the A-field page

Cons: B-Terminal Server needs to prepare a Postmessageapi page

Benefits: A better future

Browser support: chrome/firefox/safari/opera/ie10+

Client

<form method="post"><input type="file" name="Filedata" id="file"><button type="submit">submit</button></form><iframe src="http://bbb.com:8888/crossdomain/postMessage.html"></iframe>$(‘form‘).submit(function(){    var iframe = $(‘iframe‘)[0];    //向iframe的postmessate api发送消息    iframe.contentWindow.postMessage({        url : ‘http://bbb.com:8888/crossdomain/postMessage.php‘,        dataType:‘json‘,        data : {            file : $(‘input[type=file]‘)[0].files[0] //把文件数据传过去        },        contentType:false,        processData:false    }, iframe.src)    return false;})//拿到postmessageAPI返回过来的消息$(window).on(‘message‘, function(e){    var e = e.originalEvent;    alert(e.data) // {code:200}})

Postmesage.html/postmessagetapi page

//等待接受消息$(window).on(‘message‘, function(e){    var e = e.originalEvent;    var options = e.data;    var truedata = options.data;    var formdata = new FormData()    for(var prop in truedata) {        formdata.append(prop,truedata[prop]);    }       options.data = formdata;    //向postmessage.php发送ajax请求,都在b域,不跨域    $.ajax(options).always(function(result){        //把响应数据再postmessage到请求的页面        e.source.postMessage(result.responseText, e.origin)    })})

server:postMessaget.php

echo "{code:200}";
Common scenarios across subdomains

Principle: A domain aaa.aaa.com,b domain bbb.aaa.com. Both client and server returns are set document.domain = ' aaa.com '

Disadvantages: There are security risks

Benefits: More Convenient

Browser support: chrome/firefox/safari/opera/ie7+

Server

//可以设置为客户端传来的domain参数,但需要白名单<echo> "<script>document.domain=‘aaa.com‘</script>";<echo> "{code:200}";

There is a need to be aware of this scenario: IE under the short domain length of less than 5 characters can not set domain, for example www.uc.cn

Analysis of cross-domain communication/cross-domain upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.