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

Android HTTP服务器中外联JS脚本无法运行问题求助

解决HTML外联脚本无法运行的问题

问题场景

开发HTML控制台程序,主脚本文件/system/shell.js,在根目录的/sh.html中通过<script src="shell.js"></script>引入后,使用Android 11的Simple HTTP服务器测试时,脚本无法执行,但图片资源可正常加载;将脚本代码内嵌到<script>标签中则能正常运行。

测试环境:三星Galaxy A10s (A107F)、Chrome 108.0.5359.79、One UI Core 3.1

原代码示例

/sh.html

<!--/sh.html-->
<!DOCTYPE html>
<html>
    <head>
        <style>
            body {
                background-color: black;
            }
            p {
                font-family: Monospace;
                color: white;
            }
            button {
                background-color: black;
                border: 5px solid white;
                color: white;
                font-family: Monospace;
            }
        </style>
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
    </head>
    <body>
        <div id="main">
            <form>
                <table>
                    <tr>
                        <td><p>&gt;</p></td>
                        <td><input id="console-input" type="text" style="border:none;background-color:black;color:white;font-family:Monospace;"></td>
                        <td><button type="button" onclick="CmdExecute()" id="runBtn">Run</button></td>
                    </tr>
                </table>
            </form>
        </div>
        <script src="shell.js"></script>
    </body>
</html>

/system/shell.js

///system/shell.js

//import { getComArg } from "../lib/console/getArg.js"

const shSystem = {
    "console": {
        "print" : function(text) {
            addElement("p", text);
        }
    }
}

function addElement(tag, text) {
    var element = document.createElement(tag);
    element.textContent = text;
    document.body.appendChild(element);
    console.log("Created element " + tag + " with text " + text);
}

shSystem.console.print("TheShell v.0.0.2")

排查与解决方案

1. 修正脚本引入路径

原/sh.html中脚本路径为shell.js,但实际脚本位于/system/shell.js,相对路径错误导致浏览器无法找到脚本文件。将引入代码修改为:

<script src="system/shell.js"></script>

2. 检查HTTP服务器MIME类型配置

部分轻量HTTP服务器未正确配置.js文件的MIME类型,导致浏览器接收到脚本时识别为普通文本而非可执行脚本。需确保服务器对.js文件返回Content-Type: application/javascript响应头:

  • 若使用的Simple HTTP服务器支持配置,添加对应MIME规则;
  • 可更换为更规范的HTTP服务器(如Python的python -m http.server,默认支持正确的MIME类型)。

3. 清除浏览器缓存

浏览器可能缓存了旧的错误请求响应,导致脚本无法正常加载。在Chrome中长按刷新按钮,选择「清除缓存并硬刷新」,强制重新获取脚本文件。

内容的提问来源于stack exchange,提问作者kolibri_king

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 09:57:33