You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发实时代码编辑器时doc.write报Unexpected end of input错误如何解决

问题根源

你遇到的Uncaught SyntaxError: Unexpected end of input错误,核心原因是浏览器解析HTML中的JS代码时,会把模板字符串里的</script>识别为当前外层<script>标签的结束标记,直接截断后面的JS代码解析,导致代码不完整抛出语法错误。

解决方法

你只需要修改compile函数中doc.write里的</script>写法,避开浏览器的标签识别逻辑即可,有两种通用实现方案:

方案1:转义斜杠

把</script>改为<\/script>,修改后的完整代码如下:

function compile() {
  let htmlContent = document.getElementById('html');
  let cssContent = document.getElementById('css');
  let jsContent = document.getElementById('js');

  let output = document.getElementById('output');

  output = output.contentWindow || output.contentDocument.document || output.contentDocument;

  let doc = output.document;

  doc.open();
  doc.write(
    `<style>${cssContent.value}</style>
                <body>${htmlContent.value}</body>
                <script>${jsContent.value}<\/script>`
  );
  doc.close();
}

方案2:拆分拼接

把</script>拆成两部分字符串拼接,写法如下:

doc.write(
  `<style>${cssContent.value}</style>
              <body>${htmlContent.value}</body>
              <script>${jsContent.value}</` + `script>`
);

如果修改后仍触发该错误,需要检查你在JS输入框中填入的运行代码本身是否存在未闭合的括号、引号等语法问题。

内容的提问来源于stack exchange,提问作者Md. Harun Or Rashid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 23:39:01