修复端口检测:使用Vite客户端脚本检测

- 改用 @vite/client 脚本检测,这是Vite服务器必有的资源
- 移除不可靠的图片检测(vite.svg返回HTML)
- 组合script和fetch两种方法
- 修复跨域检测问题
This commit is contained in:
KQL
2025-09-24 15:29:41 +08:00
parent a86824c738
commit 60921dbfb9

View File

@@ -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;
}