通过javascript在iframe中加载html

在spring mvc中,虽然有时候,在控制器中设置返回值是json对象,但在拦截器出现错误的时候,仍然可能返回html(根据设置的不同),如果要展示这些html,最好把他们放入iframe中,以防这些html对现有页面造成污染.

let iframe = document.createElement('iframe');
iframe.style.width = "100%";
iframe.style.height = "100%";
if (!!window.ActiveXObject || "ActiveXObject" in window) {//判断是否是IE浏览器
    //对于IE,可以使用这种方式.同时,IE的iframe不支持srcdoc属性,这是唯一的方式.
    document.getElementById("someDiv").appendChild(iframe);
    iframe.contentWindow.document.open();
    iframe.contentWindow.document.write("<body>我是html代码啦啦啦</body>");
    iframe.contentWindow.document.close();
}
else {
    //对于其他浏览器,直接设置srcdoc属性就可以了.而且,如果想设置iframe.contentWindow.document也是不可能拿的,因为iframe.contentWindow根据安全策略无法访问,
    iframe.srcdoc = "<body>我是html代码啦啦啦</body>";
    document.getElementById("someDiv").appendChild(iframe);
}

 

posted on 2019-03-15 15:22  Kill_ALL_HUMANS  阅读(848)  评论(0)    收藏  举报

导航