JavaScript is required
Blog About

iframe和HTML5 blob实现JS,CSS,HTML直接当前页预览

2024/05/23
3 mins read
See this issue
# Javascript
Back

实现一个最简的网页预览页面

<!DOCTYPE html>
<html>

<head>
  <style>
    * {
      padding: 0;
      margin: 0;
    }

    html,
    body {
      height: 100%;
    }

    iframe {
      display: block;
      width: 100%;
      height: 100%;
    }
  </style>
</head>

<body>
  <iframe frameborder="0" id="iframe"></iframe>

  <script>
    // 获取iframe元素
    var iframe = document.getElementById('iframe')
    const html_content =
      `
    <style>h1 {color: red;}</style >
    <body><h1> Hello, world!</h1>
    <script>console.log('aaa') <\/script>
    `

    const iframeUrl = URL.createObjectURL(new Blob([html_content], { type: 'text/html' }))
    iframe.src = iframeUrl
  </script>
</body>

</html>

核心是怎么把静态的字符串作为网页内容传递给iframe

// 获取iframe元素
var iframe = document.getElementById('iframe')
// 传递的网页内容,注意script结束标签需要进行转义,否则会解析出错
const html_content =
  `
<style>h1 {color: red;}</style >
<body><h1> Hello, world!</h1>
<script>console.log('aaa') <\/script>
`
// 将字符串转为blob内容
const iframeUrl = URL.createObjectURL(new Blob([html_content], { type: 'text/html' }))
// iframe资源加载
iframe.src = iframeUrl

在这个原理的基础上再扩展一点就可以实现在线代码运行预览

image