跨域

本文介紹跨域的八種方法:

JSONP
只要說到跨域,就必須聊到 JSONP,JSONP全稱為:JSON with Padding,可用于解決主流瀏覽器的跨域數(shù)據(jù)訪問的問題。

Web 頁面上調(diào)用 js 文件不受瀏覽器同源策略的影響,所以通過 Script 便簽可以進行跨域的請求:

  • html中script標簽可以引入其他域下的js,不受同源策略的限制比如引入線上的jquery庫。利用這個特性,可實現(xiàn)跨域訪問接口。需要后端支持

  • script標簽:在頁面中動態(tài)插入script,script標簽的src屬性就是后端api接口的地址;這樣加載script標簽腳本直接調(diào)用本地方法,而script標簽會立即執(zhí)行腳本,示例:getNews?callback=appendHtml

  • 后端:后端需要解析callback參數(shù)值,并將該值和返回數(shù)據(jù)拼接。示例:res.send(req.query.callback + '(' + JSON.stringify(data) + ')')

后端頁面:

app.get('/getNews',function(req,res){
    var news = [
        '123',
        '456',
        '789',
        '321',
        '654',
        '987',
        '753',
        '159',
        '852'
    ]
    var data = []
    for(var i=0;i<3;i++){
        var index = parseInt(Math.random() * news.length)
        data.push(news[index])
        news.splice(index,1)
    }
   
    var cb = req.query.callback
    var show = cb + '(' + JSON.stringify(data) + ')'
    console.log(show)
    if(cb){
        res.send(show)
    }else{
        res.send(data)
    }
})

前端頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="container">
        <ul class="news">
            <li>233</li>
            <li>323</li>
            <li>332</li>
        </ul>
        <button class="change">換一組</button>
    </div>

    <script>
        let $ = (className) => document.querySelector(className)

        $('.change').addEventListener('click',function(){
            var script = document.createElement('script')
            script.src = 'http://localhost:8080/getNews?callback=appendHtml'
            document.head.appendChild(script)
            document.head.removeChild(script)
        })
        // appendHtml(["321","987","159"])
        function appendHtml(news){
            var html = ''
            for(var i=0;i<news.length;i++){
                html += '<li>' + news[i] + '</li>'
            }
            console.log(html)
            $('.news').innerHTML = html
        }
    </script>
</body>
</html>

優(yōu)點:

  • 它不像XMLHttpRequest 對象實現(xiàn) Ajax 請求那樣受到同源策略的限制
  • 兼容性很好,在古老的瀏覽器也能很好的運行
  • 不需要 XMLHttpRequest 或 ActiveX 的支持;并且在請求完畢后可以通過調(diào)用 callback 的方式回傳結(jié)果。

缺點:

  • 它支持 GET 請求而不支持 POST 等其它類行的 HTTP 請求。
  • 它只支持跨域 HTTP 請求這種情況,不能解決不同域的兩個頁面或 iframe 之間進行數(shù)據(jù)通信的問題

CORS

CORS 是一個 W3C 標準,全稱是"跨域資源共享"(Cross-origin resource sharing)它允許瀏覽器向跨源服務器,發(fā)出 XMLHttpRequest 請求,從而克服了 ajax 只能同源使用的限制。

CORS 需要瀏覽器和服務器同時支持才可以生效,對于開發(fā)者來說,CORS 通信與同源的 ajax 通信沒有差別,代碼完全一樣。瀏覽器一旦發(fā)現(xiàn) ajax 請求跨源,就會自動添加一些附加的頭信息,有時還會多出一次附加的請求,但用戶不會有感覺。

因此,實現(xiàn) CORS 通信的關(guān)鍵是服務器。只要服務器實現(xiàn)了 CORS 接口,就可以跨源通信。

首先前端先創(chuàng)建一個 index.html 頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CORS</title>
</head>
<body>
    <script>
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://127.0.0.1:3000', true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4 && xhr.status === 200) {
            alert(xhr.responseText);
        }
    }
    xhr.send(null);
    </script>
</body>
</html>

這似乎跟一次正常的異步 ajax 請求沒有什么區(qū)別,關(guān)鍵是在服務端收到請求后的處理:

require('http').createServer((req, res) => {

    res.writeHead(200, {
    'Access-Control-Allow-Origin': 'http://localhost:8080'
    });
    res.end('這是你要的數(shù)據(jù):1111');

}).listen(3000, '127.0.0.1');
console.log('啟動服務,監(jiān)聽 127.0.0.1:3000');

關(guān)鍵是在于設置相應頭中的 Access-Control-Allow-Origin,該值要與請求頭中 Origin 一致才能生效,否則將跨域失敗

成功的關(guān)鍵在于 Access-Control-Allow-Origin 是否包含請求頁面的域名,如果不包含的話,瀏覽器將認為這是一次失敗的異步請求,將會調(diào)用 xhr.onerror 中的函數(shù)

CORS 的優(yōu)缺點:

  • 使用簡單方便,更為安全
  • 支持 POST 請求方式
  • CORS 是一種新型的跨域問題的解決方案,存在兼容問題,僅支持 IE 10 以上

Server Proxy

服務器代理,顧名思義,當你需要有跨域的請求操作時發(fā)送請求給后端,讓后端幫你代為請求,然后最后將獲取的結(jié)果發(fā)送給你。
假設有這樣的一個場景,你的頁面需要獲取 CNode:Node.js專業(yè)中文社區(qū) 論壇上一些數(shù)據(jù),如通過 https://cnodejs.org/api/v1/topics,當時因為不同域,所以你可以將請求后端,讓其對該請求代為轉(zhuǎn)發(fā)。

const url = require('url');
const http = require('http');
const https = require('https');

const server = http.createServer((req, res) => {
    const path = url.parse(req.url).path.slice(1);
    if(path === 'topics') {
    https.get('https://cnodejs.org/api/v1/topics', (resp) => {
        let data = "";
        resp.on('data', chunk => {
        data += chunk;
        });
        resp.on('end', () => {
        res.writeHead(200, {
            'Content-Type': 'application/json; charset=utf-8'
        });
        res.end(data);
        });
    })      
    }
}).listen(3000, '127.0.0.1');

console.log('啟動服務,監(jiān)聽 127.0.0.1:3000');

document.domain(降域)

document.domain 的作用是用來獲取/設置當前文檔的原始域部分,例如:

// 對于文檔 www.example.xxx/good.html
document.domain="www.example.xxx"

// 對于URI http://developer.mozilla.org/en/docs/DOM 
document.domain="developer.mozilla.org"

對于主域相同而子域不同的情況下,可以通過設置document.domain 的辦法來解決,具體做法是可以在http://a.jirengu.com:8080/a.htmlhttp://b.jirengu.com:8080/b.html之中設置document.domain = 'jirengu.com'

a.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        iframe{
            width: 400px;
            height: 300px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <div class="ct">
        <h1>使用降域?qū)崿F(xiàn)跨域</h1>
        <div class="main">
            <input type="text" placeholder="http://a.jirengu.com:8080/a.html">
        </div>
        <iframe src="http://b.jirengu.com:8080/b.html"></iframe>
    </div>

    <script>
        // http://a.jirengu.com:8080/a.html
        document.querySelector('.main input').addEventListener('click',function(){
            console.log(this.value)
            window.frames[0].document.querySelector('input').value = this.value
        })
       document.domain = 'jirengu.com' 
    </script>
</body>
</html>

b.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        html,body{
            margin: 0;
            padding: 0;
        }
        input{
            margin: 20px;
            width: 200px;
        }
    </style>
</head>
<body>
    <input id="input" type="text" placeholder="http://b.jirengu.com:8080/b.html">

    <script>
        document.querySelector('#input').addEventListener('click',function(){
            window.parent.document.querySelector('input').value = this.value
        })
        document.domain = 'jirengu.com'  //降域
    </script>
</body>
</html>

document.domain 的優(yōu)點在于解決了主語相同的跨域請求,但是其缺點也是很明顯的:比如一個站點受到攻擊后,另一個站點會因此引起安全漏洞;若一個頁面中引入多個 iframe,想要操作所有的 iframe 則需要設置相同的 domain。

window.postMessage
postMessage 是 HTML5 新增加的一項功能,跨文檔消息傳輸(Cross Document Messaging),目前:Chrome 2.0+、Internet Explorer 8.0+, Firefox 3.0+, Opera 9.6+, 和 Safari 4.0+ 都支持這項功能,使用起來也特別簡單。

首先創(chuàng)建 a.html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>a.html</title>
</head>
<body>
    <iframe src="http://localhost:8081/b.html" style='display: none;'></iframe>
    <script>
    window.onload = function() {
        let targetOrigin = 'http://localhost:8081';
        window.frames[0].postMessage('我要給你發(fā)消息了!', targetOrigin);
    }
    window.addEventListener('message', function(e) {
        console.log('a.html 接收到的消息:', e.data);
    });
    </script>
</body>
</html>

創(chuàng)建一個 iframe,使用 iframe 的一個方法 postMessage 可以向http://localhost:8081/b.html 發(fā)送消息,然后監(jiān)聽 message,可以獲得其他文檔發(fā)來的消息。

同樣的 b.html 文件:

<script>
    window.addEventListener('message', function(e) {
        if(e.source != window.parent) {
        return;
        }
        let data = e.data;
        console.log('b.html 接收到的消息:', data);
        parent.postMessage('我已經(jīng)接收到消息了!', e.origin);
    });
</script>

location.hash
location.hash 是一個可讀可寫的字符串,該字符串是 URL 的錨部分(從 # 號開始的部分)。例如:

// 對于頁面 http://example.com:1234/test.htm#part2
location.hash = "#part2"

同時,由于我們知道改變 hash 并不會導致頁面刷新,所以可以利用 hash 在不同源間傳遞數(shù)據(jù)。

假設 github.io 域名下 a.html 和 shaonian.eu 域名下 b.html 存在跨域請求,那么利用 location.hash 的一個解決方案如下:

  • a.html 頁面中創(chuàng)建一個隱藏的 iframe, src 指向 b.html,其中 src 中可以通過 hash 傳入?yún)?shù)給 b.html
  • b.html 頁面在處理完傳入的 hash 后通過修改 a.html 的 hash 值達到將數(shù)據(jù)傳送給 a.html 的目的
  • a.html 頁面添加一個定時器,每隔一定時間判斷自身的 location.hash 是否變化,以此響應處理

以上步驟中需要注意第二點:如何在 iframe 頁面中修改 父親頁面的 hash 值。由于在 IE 和 Chrome 下,兩個不同域的頁面是不允許 parent.location.hash 這樣賦值的,所以對于這種情況,我們需要在父親頁面域名下添加另一個頁面來實現(xiàn)跨域請求,具體如下:

  • 假設 a.html 中 iframe 引入了 b.html, 數(shù)據(jù)需要在這兩個頁面之間傳遞,且 c.html 是一個與 a.html 同源的頁面
  • a.html 通過 iframe 將數(shù)據(jù)通過 hash 傳給 b.html
  • b.html 通過 iframe 將數(shù)據(jù)通過 hash 傳給 c.html
  • c.html 通過 parent.parent.location.hash 設置 a.html 的 hash 達到傳遞數(shù)據(jù)的目的

location.hash 方法的優(yōu)點在于可以解決域名完全不同的跨域請求,并且可以實現(xiàn)雙向通訊;而缺點則包括以下幾點:

  • 利用這種方法傳遞的數(shù)據(jù)量受到 url 大小的限制,傳遞數(shù)據(jù)類型有限
  • 由于數(shù)據(jù)直接暴露在 url 中則存在安全問題
  • 若瀏覽器不支持 onhashchange 事件,則需要通過輪訓來獲知 url 的變化
  • 有些瀏覽器會在 hash 變化時產(chǎn)生歷史記錄,因此可能影響用戶體驗

window.name
window.name的值不是一個普通的全局變量,而是當前窗口的名字,這里要注意的是每個 iframe 都有包裹它的 window,而這個 window 是top window 的子窗口,而它自然也有 window.name 的屬性,window.name 屬性的神奇之處在于 name 值在不同的頁面(甚至不同域名)加載后依舊存在(如果沒修改則值不會變化),并且可以支持非常長的 name 值(2MB)。

舉個簡單的例子:你在某個頁面的控制臺輸入:

window.name = "Hello World";window.location = "http://www.baidu.com";

頁面跳轉(zhuǎn)到了百度首頁,但是 window.name 卻被保存了下來,還是 Hello World,跨域解決方案似乎可以呼之欲出了:

首先創(chuàng)建 a.html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>a.html</title>
</head>
<body>
    <script>
    let data = '';
    const ifr = document.createElement('iframe');
    ifr.src = "http://localhost:8081/b.html";
    ifr.style.display = 'none';
    document.body.appendChild(ifr);
    ifr.onload = function() {
        ifr.onload = function() {
            data = ifr.contentWindow.name;
        console.log('收到數(shù)據(jù):', data);
        }
        ifr.src = "http://localhost:8080/c.html";
    }
    </script>
</body>
</html>

之后再創(chuàng)建 b.html 文件:

<script> window.name = "你想要的數(shù)據(jù)!";</script>

http://localhost:8080/a.html在請求遠端服務器 http://localhost:8081/b.html的數(shù)據(jù),我們可以在該頁面下新建一個 iframe,該 iframe 的 src 屬性指向服務器地址,(利用 iframe 標簽的跨域能力),服務器文件 b.html 設置好 window.name 的值。

但是由于 a.html 頁面和該頁面 iframe 的 src 如果不同源的話,則無法操作 iframe 里的任何東西,所以就取不到 iframe 的 name 值,所以我們需要在 b.html 加載完后重新?lián)Q個 src 去指向一個同源的 html 文件,或者設置成 'about:blank;' 都行,這時候我只要在 a.html 相同目錄下新建一個 c.html 的空頁面即可。如果不重新指向 src 的話直接獲取的 window.name 的話會報錯。

WebSocket
WebSocket 協(xié)議不實行同源政策,只要服務器支持,就可以通過它進行跨源通信。

參考鏈接:

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • 1. 什么是跨域? 跨域一詞從字面意思看,就是跨域名嘛,但實際上跨域的范圍絕對不止那么狹隘。具體概念如下:只要協(xié)議...
    他在發(fā)呆閱讀 829評論 0 0
  • 1. 什么是跨域? 跨域一詞從字面意思看,就是跨域名嘛,但實際上跨域的范圍絕對不止那么狹隘。具體概念如下:只要協(xié)議...
    w_zhuan閱讀 532評論 0 0
  • 前言 關(guān)于前端跨域的解決方法的多種多樣實在讓人目不暇接。以前碰到一個公司面試的場景是這樣的,好幾個人一起在等待面試...
    andreaxiang閱讀 483評論 1 4
  • 什么是跨域? 2.) 資源嵌入:、、、等dom標簽,還有樣式中background:url()、@font-fac...
    電影里的夢i閱讀 2,389評論 0 5
  • 這幾天遇到了一個小情況,領(lǐng)導開始在意產(chǎn)品的細節(jié)了,本來跟領(lǐng)導溝通的都是一些方向上面和做法上面是否穩(wěn)妥等大方面的事情...
    麥麥MW閱讀 293評論 0 0