Heim  >  Artikel  >  Web-Frontend  >  Wie JS die Browserkommunikation implementiert

Wie JS die Browserkommunikation implementiert

零到壹度
零到壹度Original
2018-03-23 11:40:332226Durchsuche

In diesem Artikel erfahren Sie hauptsächlich, wie JS die Browserkommunikation implementiert, hauptsächlich in Form von Code. Ich hoffe, dass er allen helfen kann.

Same-Origin-Richtlinie und Einschränkungen

Die Same-Origin-Richtlinie schränkt ein, wie aus derselben Quelle geladene Dokumente oder Skripte mit Ressourcen aus einer anderen Quelle interagieren können. Dies ist ein wichtiger Sicherheitsmechanismus zum Isolieren potenziell schädlicher Dateien. (Drei sind gleich: Protokoll http/https, Domänenname und Port)

  • Cookie/LocalStorage und IndexDB können nicht gelesen werden

  • DOM nicht erhalten werden

  • Ajax-Anfrage kann nicht gesendet werden

Fehlgeschlagen
URL Ergebnis Grund
http://store.company.com/dir2/other.html td> Erfolg
URL 结果 原因
http://store.company.com/dir2/other.html 成功
http://store.company.com/dir/inner/another.html 成功
https://store.company.com/secure.html 失败 不同协议 ( https和http )
http://store.company.com:81/dir/etc.html 失败 不同端口 ( 81和80)
http://news.company.com/dir/other.html 失败 不同域名 ( news和store )
http://store.company.com/dir/inner/another.html Erfolg

https://store.company.com/secure.html Misserfolg Verschiedene Protokolle (https und http)
http://store.company.com:81/dir/etc.htmlUnterschiedliche Ports (81 und 80)
http://news.company.com/dir/other.html Fehlgeschlagen Unterschiedliche Domainnamen (News und Store)
So kommunizieren Sie zwischen Front- und Back-End
  • Ajax: Kommunikationsmethode unter demselben Ursprung
  • WebSocket: Keine Einschränkungen für Same-Origin-Richtlinie
  • CORS: Unterstützt domänenübergreifende Kommunikation und Kommunikation mit demselben Ursprung

So erstellen Sie Ajax
  • Workflow des XMLHttpRequest-Objekts
  • Kompatibilitätsverarbeitung
  • Ereignisauslösebedingungen
  • Ereignisauslösesequenz
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);
        }
    }
}

Mehrere Möglichkeiten der domänenübergreifenden Kommunikation
方法 说明
JSONP 动态创建3f1c4e4b6b16bbbd69b2ee476dc4f83a标签,设置其src,回调函数在src中设置,一定要有callback=handleResponse函数,在页面中,返回的JSON作为参数传入回调函数中,我们通过回调函数来来操作数据。function handleResponse(response){// 对response数据进行操作代码}
Hash Hash是url地址中#号之后的内容,其值改变不会触发页面刷新,search是url问号后面的,一旦改变会触发刷新
postMessage window.postMessage() 方法可以安全地实现跨源通信。通常,对于两个不同页面的脚本,只有当执行它们的页面位于具有相同的协议(通常为https),端口号(443为https的默认值),以及主机  (两个页面的模数 Document.domain设置为相同的值) 时,这两个脚本才能相互通信。window.postMessage() 方法提供了一种受控机制来规避此限制,只要正确的使用,这种方法就很安全。https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage
WebSocket 不受同源策略影响https://developer.mozilla.org/zh-CN/docs/Web/API/WebSocket
CORS 全称是”跨域资源共享”(Cross-origin resource sharing)具体来说,就是在头信息之中,增加一个Origin字段。Origin字段用来说明,本次请求来自哪个源(协议 + 域名 + 端口)。

Hash-Detaillierte Erklärung:
// 利用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){
  })

Das obige ist der detaillierte Inhalt vonWie JS die Browserkommunikation implementiert. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn