js是如何实现跨域的?教你几种方式
发布时间:2022-01-11 17:11:08 所属栏目:语言 来源:互联网
导读:本文给大家分享是的JS跨域的内容,由于同源策略的限制,满足同源的脚本才可以获取资源。虽然这样有助于保障网络安全,但另一方面也限制了资源的使用。那么js是如何实现跨域的呢?接下来给大家分享八种方式实现跨域的方案。 一、jsonp跨域 原理:script标签引
本文给大家分享是的JS跨域的内容,由于同源策略的限制,满足同源的脚本才可以获取资源。虽然这样有助于保障网络安全,但另一方面也限制了资源的使用。那么js是如何实现跨域的呢?接下来给大家分享八种方式实现跨域的方案。 一、jsonp跨域 原理:script标签引入js文件不受跨域影响。不仅如此,带src属性的标签都不受同源策略的影响。 正是基于这个特性,我们通过script标签的src属性加载资源,数据放在src属性指向的服务器上,使用json格式。 由于我们无法判断script的src的加载状态,并不知道数据有没有获取完成,所以事先会定义好处理函数。服务端会在数据开头加上这个函数名,等全部加载完毕,便会调用我们事先定义好的函数,这时函数的实参传入的就是后端返回的数据了。 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> function callback(data) { alert(data.test); } </script> <script src="./jsonp.js"></script> </body> </html> jsonp.js callback({"test": 0}); 访问index.html弹窗便会显示0 该方案的缺点是:只能实现get一种请求。 二、document.domain + iframe跨域 此方案仅限主域相同,子域不同的应用场景。 比如百度的主网页是www.baidu.com,zhidao.baidu.com、news.baidu.com等网站是www.baidu.com这个主域下的子域。 实现原理:两个页面都通过js设置document.domain为基础主域,就实现了同域,就可以互相操作资源了。 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <iframe src="https://mfaying.github.io/lesson/cross-origin/document-domain/child.html"></iframe> <script> document.domain = 'mfaying.github.io'; var t = '0'; </script> </body> </html> child.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> document.domain = 'mfaying.github.io'; alert(window.parent.t); </script> </body> </html> 三、location.hash + iframe跨域 父页面改变iframe的src属性,location.hash的值改变,不会刷新页面(还是同一个页面),在子页面可以通过window.localtion.hash获取值。 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <iframe src="child.html#" style="display: none;"></iframe> <script> var oIf = document.getElementsByTagName('iframe')[0]; document.addEventListener('click', function () { oIf.src += '0'; }, false); </script> </body> </html> child.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> window.onhashchange = function() { alert(window.location.hash.slice(1)); } </script> </body> </html> 点击index.html页面弹窗便会显示0 四、window.name + iframe跨域 原理:window.name属性在不同的页面(甚至不同域名)加载后依旧存在,name可赋较长的值(2MB)。 在iframe非同源的页面下设置了window的name属性,再将iframe指向同源的页面,此时window的name属性值不变,从而实现了跨域获取数据。 ./parent/index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> var oIf = document.createElement('iframe'); oIf.src = 'https://mfaying.github.io/lesson/cross-origin/window-name/child.html'; var state = 0; oIf.onload = function () { if (state === 0) { state = 1; oIf.src = 'https://mfaying.github.io/lesson/cross-origin/window-name/parent/proxy.html'; } else { alert(JSON.parse(oIf.contentWindow.name).test); } } document.body.appendChild(oIf); </script> </body> </html> ./parent/proxy.html 空文件,仅做代理页面 ./child.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> window.name = '{"test": 0}' </script> </body> </html> 五、postMessage跨域 postMessage是HTML5提出的,可以实现跨文档消息传输。 用法 getMessageHTML.postMessage(data, origin); data: html5规范支持的任意基本类型或可复制的对象,但部分浏览器只支持字符串,所以传参时最好用JSON.stringify()序列化。 origin: 协议+主机+端口号,也可以设置为"*",表示可以传递给任意窗口,如果要指定和当前窗口同源的话设置为"/"。 getMessageHTML是我们对于要接受信息页面的引用,可以是iframe的contentWindow属性、window.open的返回值、通过name或下标从window.frames取到的值。 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <iframe id='ifr' src='./child.html' style="display: none;"></iframe> <button id='btn'>click</button> <script> var btn = document.getElementById('btn'); btn.addEventListener('click', function () { var ifr = document.getElementById('ifr'); ifr.contentWindow.postMessage(0, '*'); }, false); </script> </body> </html> child.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> window.addEventListener('message', function(event){ alert(event.data); }, false); </script> </body> </html> 点击index.html页面上的按钮,弹窗便会显示0。 六、跨域资源共享(CORS) 只要在服务端设置Access-Control-Allow-Origin就可以实现跨域请求,若是cookie请求,前后端都需要设置。 由于同源策略的限制,所读取的cookie为跨域请求接口所在域的cookie,并非当前页的cookie。 CORS是目前主流的跨域解决方案。 原生node.js实现 index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> </head> <body> <script> $.get('http://localhost:8080', function (data) { alert(data); }); </script> </body> </html> server.js var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'Access-Control-Allow-Credentials': 'true', // 后端允许发送Cookie 'Access-Control-Allow-Origin': 'https://mfaying.github.io', // 允许访问的域(协议+域名+端口) 'Set-Cookie': 'key=1;Path=/;Domain=mfaying.github.io;HttpOnly' // HttpOnly:脚本无法读取cookie }); res.write(JSON.stringify(req.method)); res.end(); }); server.listen('8080'); console.log('Server is running at port 8080...'); (编辑:站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |