Home  >  Article  >  Web Front-end  >  How JS implements browser communication

How JS implements browser communication

零到壹度
零到壹度Original
2018-03-23 11:40:332265browse

This article mainly shares with you how JS implements browser communication, mainly in the form of code. I hope it can help everyone.

Same-origin policy and restrictions

The same-origin policy restricts how documents or scripts loaded from the same source interact with resources from another source. This is an important security mechanism for isolating potentially malicious files. (Three are the same: protocol http/https, domain name and port)

  • Cookie/LocalStorage and IndexDB cannot be read

  • DOM cannot be obtained

  • Ajax request cannot be sent

##URLResult Reasonhttp://store.company.com/dir2/other.htmlSuccesshttp://store.company.com/dir/inner/another.htmlSuccesshttps://store.company.com/secure.htmlFailedDifferent protocols (https and http)http://store.company.com:81/dir/etc.htmlFailedDifferent ports (81 and 80)http://news.company.com/dir/other.htmlFailureDifferent domain names (news and store)


How to communicate between the front and back ends

  • Ajax: Communication method under the same origin

  • WebSocket: No restriction on the same origin policy

  • CORS: supports cross-domain communication and also supports same-origin communication

How to create Ajax

  • XMLHttpRequest object workflow

  • Compatibility processing

  • Event triggering conditions

  • Event triggering sequence

  • var xht = XMLHttpRequest ? new XMLHttpRequest():new window.ActiveXObject('Microsoft.XMLHTTP');var data = opt.data,
        url = opt.url,
        type=opt.type.toUpperCase(),
        dataArr=[];for(var k in data){
        dataArr.push(k+'='+data[k]);
    }if(type === 'GET'){
        url = url + '?' + dataArr.join("&");
        xhr.open(type, url.replace(/\?s/g,''), true);
        xhr.send();
    }if(type === 'POST'){
        xhr.open(type, url, true);
        xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        xhr.send(dataArr.join('&'));
    }
    xhr.onload = function(){
        if(xhr.status === 200 || xhr.status === 304){ //媒体资源需要206
            var res;        if(opt.success && opt.success instanceof Function){
                res = xhr.responseText;            if(typeof res === 'string'){
                    res = JSON.parse(res);
                    opt.success.call(xhr, res);
                }
            }
        }else{        if(opt.error && opt.error instanceof Function){
                opt.error.call(xhr, res);
            }
        }
    }
Several ways of cross-domain communication

MethodDescriptionJSONPDynamicly create the HashHash is the content after the # number in the url address , its value change will not trigger a page refresh. The search is after the question mark in the url. Once changed, a refresh will be triggered. postMessagewindow.postMessage() method can be safely used Enable cross-source communication. Typically, scripts for two different pages will only execute if the page they are executed on is located on a page with the same protocol (usually https), port number (443 is the default for https), and host (modulo Document.domain of both pages). set to the same value) for the two scripts to communicate with each other. The window.postMessage() method provides a controlled mechanism to circumvent this limitation and is safe as long as it is used correctly. https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessageWebSocketis not affected by the same origin policy https: //developer.mozilla.org/zh-CN/docs/Web/API/WebSocketCORS stands for "Cross-origin Resource Sharing" resource sharing) Specifically, it means adding an Origin field to the header information. The Origin field is used to indicate which source this request comes from (protocol + domain name + port).
3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, set its src, the callback function is set in src, there must be callback=handleResponseFunction, in the page, the returned JSON is passed into the callback function as a parameter, and we use the callback function to operate the data. function handleResponse(response){//Operation code for response data}
Hash detailed explanation:

// 利用Hash,场景是当前页面A通过iframe或者frame嵌入了跨域页面B//A中伪代码如下:var B = document.getElelementByTagName('iframe');
B.src = B.src + '#' + 'data';// B中伪代码window.onhashchange = function(){
    var data = window.location.hash;
}

postMessage

// 窗口A(http://A.com)向跨域的窗口B(http://B.com)发送信息window.postMessage(data, "http://B.com");()//在窗口监听window.addEventListener('message', function(event){
    console.log(event.origin)//http://A.com
    console.log(event.source)//引用A window
    console.log(event.data) //数据}, false)

WebSocket

var ws = new WebSocket('wss://a.com');
//ws 类似http为非加密,wss类似https为加密
ws.onopen = function(){}//打开链接
ws.onmessage = function(){}//收到消息
ws.onclose = function(){}//关闭连接

CORS

//使用 fetch 的构造函数请求数据后,返回一个 Promise 对象,处理即可。
//Fetch 常见坑
//Fetch 请求默认是不带 cookie 的,需要设置 fetch(url, {credentials: 'include'})
//服务器返回 400,500 错误码时并不会 reject,只有网络错误这些导致请求不能完成时,fetch 才会被 reject。
 fetch("/some/url", {
    method:'get
 '}).then(function(response){
    }).catch(function(err){
  })

The above is the detailed content of How JS implements browser communication. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn