【Javascript】Content-Security-Policy upgrade-insecure-requests

業務場景

在 https 協議下使用阿里雲的 OSS 直傳功能時,會出現相關錯誤提示導致圖片無法上傳

解決方案

可以在客戶端頁面 head 元素中添加 CSP meta 標籤來解決,可參考如下資料:
https://cloud.tencent.com/developer/section/1189878

代碼示例

function set_content_security_policy() {
    if (window.location.protocol == 'http:') return;

    var metas = document.getElementsByTagName("meta");
    var has_set = false;
    for (var i = 0; i < metas.length; i++) {
        if (metas[i].getAttributeNode("http-equiv") != null &&
            metas[i].getAttributeNode("http-equiv").value == "Content-Security-Policy" &&
            metas[i].getAttributeNode("content") != null &&
            metas[i].getAttributeNode("content").value == "upgrade-insecure-requests"
        ) {
            has_set = true;
            break;
        }
    }
    if (!has_set) {
        var meta_new = document.createElement("META");
        var http_equiv = document.createAttribute("http-equiv");
        var content = document.createAttribute("content");
        http_equiv.value = "Content-Security-Policy";
        content.value = "upgrade-insecure-requests";
        meta_new.setAttributeNode(http_equiv);
        meta_new.setAttributeNode(content);
        document.getElementsByTagName("head")[0].appendChild(meta_new);
    }
}

參考資料

https://cloud.tencent.com/developer/section/1189878
http://www.ruanyifeng.com/blog/2016/09/csp.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章