iframe在項目中實戰問題

1、應用場景

  • web項目中須要引用第三方的頁面,例如調用第三方的收銀臺(支付寶、銀行、微信等等)

2、正常使用

  • 直接嵌套使用iframe標籤,iframe
<iframe src="https://www.w3school.com.cn/tags/tag_iframe.asp" frameborder="0"></iframe>
複製代碼

3、使用中問題

  • 一、 若是iframe中的src地址是https的地址,iframe打開時會設置爲http打開,會致使沒法打開頁面,並在控制檯報錯。
  • 解決方法:在HTMLhead中添加如下代碼(添加如下代碼後,全部的請求都會升級爲https,因此要本地或開發環境使用http須要把如下代碼註釋掉)
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
複製代碼
  • 二、當打開頁面後,iframe打開一個錯誤頁面關閉後,從新再打開依舊是以前的頁面,緣由是iframe會緩存以前打開的頁面,因此咱們在使用時應該動態去建立iframe標籤
  • 解決方法:
const iframe = document.createElement("iframe");
iframe.src = src
iframe.style.width = '100%';
iframe.style.height = '100%';
iframe.style.border = 'none';
if (data) {
    if (navigator.userAgent.indexOf("MSIE") > -1 && !window.opera) {
        iframe.onreadystatechange = function () {
            if (iframe.readyState === "complete") {
                iframe.contentWindow.postMessage(JSON.stringify(data), '*')
            }
        };
    } else {
        iframe.onload = function () {
            iframe.contentWindow.postMessage(JSON.stringify(data), '*')
        };
    }
}
document.getElementById(id).appendChild(iframe);
複製代碼
相關文章
相關標籤/搜索