一、应用场景
- 在
web项目中需要引用第三方的页面,例如调用第三方的收银台(支付宝、银行、微信等等)
二、正常使用
<iframe src="https://www.w3school.com.cn/tags/tag_iframe.asp" frameborder="0"></iframe>
三、使用中问题
- 1、 如果
iframe中的src地址是https的地址,iframe打开时会设置为http打开,会导致无法打开页面,并在控制台报错。

- 解决方法:在
HTML的head中添加以下代码(添加以下代码后,所有的请求都会升级为https,所以要本地或开发环境使用http需要把以下代码注释掉)
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
- 2、当打开页面后,
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);