前端实现跨域的几种方法

为什么会有跨域?那必须得说同源政策,同源指的是三个同源:1,协议相同,域名相同,端口相同,例如http://y.localhost.com:7001/public/3.html;这些网址协议是http://域名是y.localhost.com:,端口号是7001,在这三个都相同的话就是同源
同源:http://y.localhost.com:7001/public/5.html,
同域不同端口http://y.localhost.com:7002/public/3.html,
协议不同https://y.localhost.com:7001/public/3.html
域不同http://x.localhost.com:7001/public/3.html,
不同源的网址不能不可以共享cookie,LocalStorage ,dom也无法获取,ajax不能发送,防止了恶意的网站窃取数据,保证了用户信息的安全,所以同源政策是必须的,
但是也给开发人员带来了不便。那解决同源政策有这几种方法:
1.window+哈希值+iframe
http://y.localhost.com:7001/public/1.html页面的js:

var iframe = document.createElement('iframe')
iframe.src = 'http://x.localhost.com:7001/public/hash.html'
document.body.appendChild(iframe)

window.onhashchange = function() {
    // 当哈希值改变时会执行此方法

    console.log(location.hash)
}

http://x.localhost.com:7001/public/1.html 页面的js

setTimeout(() => {

    parent.location.href = `http://y.localhost.com:7001/public/3.html#msg=123`;
}, 500);

原理是通过iframe的子页面通过异步获取数据,然后将数据绑定在哈希值上面,利用parent.location.href来给不同域名的父级添加哈希值,但是网址改变哈希值时并不会刷新页面,并且可以监听哈希值变化来获取子页面传来的值
2.window.name+iframe
http://y.localhost.com:7001/public/2.html页面的js:

var iframe = document.createElement('iframe')
iframe.src = 'http://x.localhost.com:7001/public/name.html'//不同域名的网址
document.body.appendChild(iframe)
iframe.onload = function() {
    console.log(iframe.contentWindow.name)
}

http://x.localhost.com:7001/public/2.html页面的js:

setTimeout(() => {
            window.name = "abc";
            location.href = 'http://y.localhost.com:7001/public/index.html'  //一个空的页面用来传name值
        }, 1);

原理:利用window.name有一个特性,只要是在同一个窗口,前一个网页设置name后面一个网页也能读取到name,因此可以利用iframe跨域的子页面通过请求完异步之后在跳转到跟父级页面域名相同的网页,你可以把异步的信息存在window.name上面,此时窗口没有改变,只是改变了网址,window。name依然存在,此时的ifram父子页面的url是同源,所以就能通过iframe.contentWindow.name获取window.name了
3、window.postMessageHTML5的API,
4.AJAX通信的三种方式:jsonp,cors,WebSocket;以后在详细补充

你可能感兴趣的:(前端跨域的写法)