diff --git a/src/hooks/useShorturlchange.js b/src/hooks/useShorturlchange.js index 2d01cc3..228568f 100644 --- a/src/hooks/useShorturlchange.js +++ b/src/hooks/useShorturlchange.js @@ -53,34 +53,26 @@ const useShortUrlChange = () => { } }; const normalizeUrl = (longUrl) => { - const trimmed = longUrl.trim(); - // 排除纯数字、纯字母、纯文字(中文、日文等)以及它们的组合 - if (/^[\p{L}\p{N}]+$/u.test(trimmed)) { - return ''; - } - if (!trimmed) return ''; - - // 1. 已是 http/https 开头,直接验证合法性 - if (/^https?:\/\//i.test(trimmed)) { - try { - const urlObj = new URL(trimmed); - return urlObj.href; - } catch (e) { - return ''; - } - } - // 2. www 开头/纯域名/IP+端口,补 https:// 后验证 - const fullUrl = `https://${trimmed}`; try { - const urlObj = new URL(fullUrl); - return urlObj.href; + const hasProtocol = /^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//.test(longUrl); + const url = new URL(hasProtocol ? longUrl : `http://${longUrl}`); + const params = Object.fromEntries(url.searchParams.entries()); + + return { + url: url.href, + valid: true, + origin: url.origin, + hostname: url.hostname, + pathname: url.pathname, + params + }; } catch (e) { - return ''; + return { valid: false, error: "Invalid URL" }; } }; const convertUrl = useCallback(async (longUrl) => { const normalizedUrl = normalizeUrl(longUrl); - if (!normalizedUrl) { + if (!normalizedUrl.valid || Object.keys(normalizedUrl?.params || {}).length === 0) { setGlobalNotify([{ key: Date.now().toString(), title: '错误', @@ -90,7 +82,7 @@ const useShortUrlChange = () => { return null; } - const { base64Url, extracted2 } = urlBase64(normalizedUrl); + const { base64Url, extracted2 } = urlBase64(normalizedUrl.url); if (base64Url) { const apiUrl = apiPrefix[extracted2] || apiPrefix["chinahighlights.com"]; @@ -110,7 +102,7 @@ const useShortUrlChange = () => { setGlobalNotify([{ key: Date.now().toString(), title: '错误', - content: '转换失败,请检查输入的URL是否正确', + content: '转换失败,请检查输入的URL是否正确!', type: 'error' }]); return null;