Mixed Content: 資源載入失敗
阿新 • • 發佈:2021-01-15
文章目錄
原因
當一個https的網站,發出了http的請求,就會出現以下的情況。
谷歌瀏覽器中
The page at 'https://active-mixed-content.glitch.me/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://active-mixed-content.glitch.me/xmlhttprequest-data.js' . This request has been blocked; the content must be served over HTTPS
火狐中
已阻止載入混合活動內容“http://active-mixed-content.glitch.me/insecure-styles.css”
特點
Passsive mixed content
值得注意的是,未必所有的mixed content都會載入失敗,對於以下的資源,仍舊是可以成功載入的。
這些資源包括:
- 圖片
- 視訊
- 音訊
如下圖:這些資源雖然是mixed content,但仍舊可以成功載入,只不過丟擲了警告。
以上的資源稱為passive mixed content
Active mixed content
相比而言,active mixed content,則是很危險的mixed content,比如一個指令碼檔案被中間人劫持,可能導致使用者提交表單資料中的關鍵資訊的洩露。所以這些資源是不被允許載入的。
這種型別的資源包含:
- <script>
- <link>
- <iframe>
- XMLHttpRequest
- fetch 請求
- <object>
解決
遇到這個問題,我們需要通過升級http的請求到https,保證資源可以被載入。
在引用外部資原始檔的時候,可以通過//
來代替https://
或者http://
:
<!-- 使用以下的方式 -->
<script src="//cdn.domain.com/your-file.js"></script>
<!-- 而不是 -->
<script src="http://cdn.domain.com/your-file.js"></script>
<!-- 或者 -->
<script src="https://cdn.domain.com/your-file.js"></script>
//
會自動根據當前頁面協議來決定自身載入所使用的協議。進而保證當前載入的資原始檔不出現mixed content。