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);
复制代码
相关文章
相关标签/搜索