跨域

作者: 事在人为s | 来源:发表于2020-04-09 20:37 被阅读0次

同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

不受同源策略限制的<script src="..."></script>,<img>,<link>,<iframe>

5种跨域的方法

jsonp

不是ajax,利用 <script></script>标签可跨域的特性

<script src="http://www.abc.com/?data=name&callback=jsonp" charset="utf-8"></script>

<script type="text/javascript">
        jsonp({
            data: {

            },
        });
</script>

hash

// 利用hash,场景是当前页面 A 通过iframe或frame嵌入了跨域的页面 B
// 在A中伪代码如下:
var B = document.getElementsByTagName('iframe');
B.src = B.src + '#' + 'data';
// 在B中的伪代码如下
window.onhashchange = function() {
    var data = window.location.hash;
};

postMessage

h5 新特性

// 窗口A(http:A.com)向跨域的窗口B(http:B.com)发送信息
Bwindow.postMessage('data', 'http://B.com');
// 在窗口B中监听
Awindow.addEventListener('message', function(event) {
    console.log(event.origin);
    console.log(event.source);
    console.log(event.data);
}, false);

WebSocket

h5 新特性

var ws = new WebSocket('wss://echo.websocket.org');

ws.onopen = function(evt) {
    console.log('Connection open ...');
    ws.send('Hello WebSockets!');
};

ws.onmessage = function(evt) {
    console.log('Received Message: ', evt.data);
    ws.close();
};

ws.onclose = function(evt) {
    console.log('Connection closed.');
};

CORS 跨域资源共享

fetch('/some/url/', {
    method: 'get',
}).then(function(response) {

}).catch(function(err) {
    // 出错了,等价于 then 的第二个参数,但这样更好用更直观
});

相关文章

网友评论

    本文标题:跨域

    本文链接:https://www.haomeiwen.com/subject/tgmhmhtx.html