Home > Web Front-end > JS Tutorial > body text

How JS implements browser communication

零到壹度
Release: 2018-03-23 11:40:33
Original
2277 people have browsed it

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);
            }
        }
    }
    Copy after login
Several ways of cross-domain communication

MethodDescriptionJSONPDynamicly create the
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template