您好,欢迎来到吃客养生。
搜索
您的当前位置:首页JS如何实现浏览器通信

JS如何实现浏览器通信

来源:吃客养生


本文主要和大家分享JS如何实现浏览器通信,主要以代码形式,希望能帮助到大家。

同源策略及

同源策略了从同一个源加载的文档或脚本如何与来自另一个源的资源进行交互。这是一个用于隔离潜在恶意文件的重要安全机制。(三相同:协议http/https,域名和端口)

  • Cookie/LocalStorage和IndexDB无法读取

  • DOM无法获得

  • Ajax请求不能发发送

  • 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 )

    前后端如何通信

  • Ajax:同源下通信方式

  • WebSocket:不同源策略

  • CORS:支持跨域通信,也支持同源通信

  • 如何创建Ajax

  • XMLHttpRequest对象的工作流程

  • 兼容性处理

  • 事件的触发条件

  • 事件的触发顺序

  • 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);
     }
     }
    }

    跨域通信的几种方式

    方法说明
    JSONP动态创建<script>标签,设置其src,回调函数在src中设置,一定要有callback=handleResponse函数,在页面中,返回的JSON作为参数传入回调函数中,我们通过回调函数来来操作数据。function handleResponse(response){// 对response数据进行操作代码}
    HashHash是url地址中#号之后的内容,其值改变不会触发页面刷新,search是url问号后面的,一旦改变会触发刷新
    postMessagewindow.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详解:

    // 利用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){
     })

    Copyright © 2019- ckry.cn 版权所有

    违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

    本站由北京市万商天勤律师事务所王兴未律师提供法律服务