1、應用場景
- 在
web
項目中須要引用第三方的頁面,例如調用第三方的收銀臺(支付寶、銀行、微信等等)
2、正常使用
<iframe src="https://www.w3school.com.cn/tags/tag_iframe.asp" frameborder="0"></iframe>
複製代碼
3、使用中問題
- 一、 若是
iframe
中的src
地址是https
的地址,iframe
打開時會設置爲http
打開,會致使沒法打開頁面,並在控制檯報錯。
- 解決方法:在
HTML
的head
中添加如下代碼(添加如下代碼後,全部的請求都會升級爲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);
複製代碼