/** * 微信环境检测工具 * 用于检测是否在微信浏览器中,并提供跳转浏览器的功能 */ /** * 检测是否在微信环境中 * @returns {boolean} 是否在微信中 */ export function isWechat(): boolean { const ua = navigator.userAgent.toLowerCase(); return /micromessenger/.test(ua); } /** * 检测平台类型 * @returns {object} 平台信息 */ export function getPlatform() { const ua = navigator.userAgent.toLowerCase(); return { isAndroid: /android/.test(ua), isIOS: /iphone|ipad|ipod/.test(ua), isWechat: /micromessenger/.test(ua), }; } /** * 尝试在浏览器中打开当前页面 * @param {string} url - 要打开的URL,默认为当前页面URL * @returns {boolean} 是否成功触发跳转 */ export function openInBrowser(url?: string): boolean { const targetUrl = url || window.location.href; const platform = getPlatform(); try { if (platform.isAndroid) { // 安卓可以直接尝试打开浏览器 // 方法1: 尝试使用 intent:// 协议(适用于微信内置浏览器) try { const urlObj = new URL(targetUrl); const intentUrl = `intent://${urlObj.host}${urlObj.pathname}${urlObj.search}#Intent;scheme=https;package=com.android.chrome;end`; // 使用隐藏的 iframe 尝试跳转 const iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.style.width = '1px'; iframe.style.height = '1px'; iframe.src = intentUrl; document.body.appendChild(iframe); // 延迟移除 iframe,给跳转一些时间 setTimeout(() => { try { document.body.removeChild(iframe); } catch (e) { // 忽略移除失败 } }, 1000); // 同时尝试直接跳转(作为备选方案) setTimeout(() => { window.location.href = targetUrl; }, 500); return true; } catch (e) { // 如果 intent 失败,直接跳转 window.location.href = targetUrl; return true; } } else if (platform.isIOS) { // iOS 在微信中无法直接跳转,需要用户手动操作 // 这里尝试直接跳转(可能会失败,但至少尝试) window.location.href = targetUrl; return true; } else { // 其他平台直接跳转 window.location.href = targetUrl; return true; } } catch (error) { return false; } } /** * 复制链接到剪贴板 * @param {string} url - 要复制的URL,默认为当前页面URL * @returns {Promise} 是否成功复制 */ export async function copyToClipboard(url?: string): Promise { const targetUrl = url || window.location.href; try { if (navigator.clipboard && navigator.clipboard.writeText) { await navigator.clipboard.writeText(targetUrl); return true; } else { // 降级方案:使用传统的复制方法 const textArea = document.createElement('textarea'); textArea.value = targetUrl; textArea.style.position = 'fixed'; textArea.style.left = '-999999px'; textArea.style.top = '-999999px'; document.body.appendChild(textArea); textArea.focus(); textArea.select(); try { const successful = document.execCommand('copy'); document.body.removeChild(textArea); return successful; } catch (err) { document.body.removeChild(textArea); return false; } } } catch (error) { return false; } }