From 60921dbfb94721dbc36b759d02879f4817b42190 Mon Sep 17 00:00:00 2001 From: KQL Date: Wed, 24 Sep 2025 15:29:41 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=AB=AF=E5=8F=A3=E6=A3=80?= =?UTF-8?q?=E6=B5=8B=EF=BC=9A=E4=BD=BF=E7=94=A8Vite=E5=AE=A2=E6=88=B7?= =?UTF-8?q?=E7=AB=AF=E8=84=9A=E6=9C=AC=E6=A3=80=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 改用 @vite/client 脚本检测,这是Vite服务器必有的资源 - 移除不可靠的图片检测(vite.svg返回HTML) - 组合script和fetch两种方法 - 修复跨域检测问题 --- index.html | 60 +++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/index.html b/index.html index 35a7493..d1472d3 100644 --- a/index.html +++ b/index.html @@ -564,42 +564,82 @@ // 实际的端口检查逻辑 async function checkPort(port) { - // 方法1: 使用Image检测 - const checkImage = () => { + // 使用多种方法组合检测 + + // 方法1: 检测Vite客户端脚本 + const checkViteClient = () => { return new Promise((resolve) => { - const img = new Image(); + const script = document.createElement('script'); let resolved = false; const timeout = setTimeout(() => { if (!resolved) { resolved = true; + if (script.parentNode) { + script.parentNode.removeChild(script); + } resolve(false); } - }, 2000); + }, 1500); - img.onload = () => { + script.onload = () => { if (!resolved) { resolved = true; clearTimeout(timeout); + script.parentNode.removeChild(script); resolve(true); } }; - img.onerror = () => { + script.onerror = () => { if (!resolved) { resolved = true; clearTimeout(timeout); + if (script.parentNode) { + script.parentNode.removeChild(script); + } resolve(false); } }; - // 添加时间戳避免缓存 - img.src = `http://localhost:${port}/vite.svg?_=${Date.now()}`; + // Vite开发服务器总是有这个客户端脚本 + script.src = `http://localhost:${port}/@vite/client?_=${Date.now()}`; + script.async = true; + document.head.appendChild(script); }); }; - // 执行检查 - const result = await checkImage(); + // 方法2: 使用fetch检测根路径 + const checkFetch = () => { + return new Promise((resolve) => { + const controller = new AbortController(); + const timeout = setTimeout(() => { + controller.abort(); + resolve(false); + }, 1500); + + fetch(`http://localhost:${port}/`, { + signal: controller.signal, + mode: 'no-cors', + cache: 'no-cache' + }).then(() => { + clearTimeout(timeout); + resolve(true); + }).catch(() => { + clearTimeout(timeout); + resolve(false); + }); + }); + }; + + // 先尝试Vite客户端检测 + let result = await checkViteClient(); + + // 如果Vite客户端检测失败,尝试fetch + if (!result) { + result = await checkFetch(); + } + return result; }