美文网首页
iframe 之 document.write() 的使用

iframe 之 document.write() 的使用

作者: 一沭丶 | 来源:发表于2019-01-23 11:26 被阅读36次
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>top</title>
    <link rel="stylesheet" href="">
    <style>
        .iframe {
            width: 400px;
            height: 400px;
            border: 1px solid #f00;
        }
    </style>
</head>
<body>
    <div>
        这是top
    </div>
    <iframe class="iframe" id="iframe" frameborder="0"></iframe>

    <script>
        var iframe = document.getElementById('iframe');

        // iframe.contentWindow.document.open();
        iframe.contentWindow.document.write(`<!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <meta http-equiv="X-UA-Compatible" content="ie=edge">
          <title>demo预览</title>
          <style>
            .div {
                height: 100px;
                width: 100px;
                background: #f60;
            }
          <\/style>
      </head>
      <body>
          <div class="div">123</div>
          <script src="jquery-1.12.4.min.js"><\/script>
          <script>
            console.log(111);
            $(function(){
                console.log(222);
            })
            window.onload = function() {
                console.log('onload');
            }

            console.log($('.div').text());
            console.log(333);
          <\/script>
      </body>
      </html>`)

        // iframe.contentWindow.document.close();
        
        iframe.onload = function() {
            console.log('iframe is loaded')
        }
    </script>
</body>
</html>

关于 iframe.contentWindow.document.open();iframe.contentWindow.document.close();

不使用:

image.png

使用后:

image.png

可以看到原本 iframe 中的 onload 事件和 $(function() {}) 都没有触发,切父页面中 onload 事件也没有触发。

document.open 文档

如果没有使用 document.close ,则浏览器一直在加载状态,如下图所示

image.png image.png

相关文章

  • iframe 之 document.write() 的使用

    关于 iframe.contentWindow.document.open(); 和 iframe.conten...

  • 页面性能优化笔记

    避免使用document.write 目的尽可能避免使用 document.write ,因为可能会冲掉页面原有的...

  • iframe标签与a标签的使用

    iframe定义及用法(使用iframe页面会很卡不建议使用) iframe默认高度为50px,宽度为100px;...

  • 改变this指向(转)

    我们在js中可以使用document.write()方法向网页中输入文本内容。如 document.write("...

  • 不打开新页面下载文件

    1. 使用IFrame 2. IFrame 模拟POST请求 3. 使用a 标签 4.XMLHttpRequest...

  • 文件导出二

    使用iframe 导出

  • 前端预览PDF,Excel,Word,TXT文件

    前端可以使用iframe可以直接预览文件,以下是几种依靠iframe实现在线预览的解决方案。