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);
复制代码