diff --git a/public/proxy/content.js b/public/proxy/content.js index 80096b7..b00d962 100644 --- a/public/proxy/content.js +++ b/public/proxy/content.js @@ -1,213 +1,220 @@ console.log("Content script starting..."); -// 代理操作类型常量 -const ProxyActionType = { - SET_PROXY_CONFIG: 'SET_PROXY_CONFIG', - CLEAR_PROXY_CONFIG: 'CLEAR_PROXY_CONFIG', - GET_PROXY_STATUS: 'GET_PROXY_STATUS', - GET_PROXY_CONFIGS: 'GET_PROXY_CONFIGS', - UPDATE_PROXY_CONFIG: 'UPDATE_PROXY_CONFIG' -}; +(function () { + // 检查是否为 HTML 文档 + if (document.documentElement?.nodeName.toLowerCase() !== 'html') { + console.log("Not an HTML document, content script will not run"); + return; + } -// 在文件顶部添加常量声明 -const YAK_ICON_URL = chrome.runtime.getURL('/images/yak.svg'); + // 代理操作类型常量 + const ProxyActionType = { + SET_PROXY_CONFIG: "SET_PROXY_CONFIG", + CLEAR_PROXY_CONFIG: "CLEAR_PROXY_CONFIG", + GET_PROXY_STATUS: "GET_PROXY_STATUS", + GET_PROXY_CONFIGS: "GET_PROXY_CONFIGS", + UPDATE_PROXY_CONFIG: "UPDATE_PROXY_CONFIG", + }; -// 添加一个通用的消息发送函数 -async function sendMessageWithRetry(message, maxRetries = 3) { - for (let i = 0; i < maxRetries; i++) { + // 在文件顶部添加常量声明 + const YAK_ICON_URL = chrome.runtime.getURL("/images/yak.svg"); + + // 添加一个通用的消息发送函数 + async function sendMessageWithRetry(message, maxRetries = 3) { + for (let i = 0; i < maxRetries; i++) { + try { + return await chrome.runtime.sendMessage(message); + } catch (error) { + console.warn(`Attempt ${i + 1} failed:`, error); + if (i === maxRetries - 1) { + throw error; + } + // 等待一小段时间后重试 + await new Promise((resolve) => setTimeout(resolve, 500)); + } + } + } + + // 获取当前代理状态 + async function getCurrentProxy() { try { - return await chrome.runtime.sendMessage(message); + const response = await sendMessageWithRetry({ + action: ProxyActionType.GET_PROXY_STATUS, + }); + + if (!response || !response.success) { + console.log("No valid response from background script"); + return {enable: false, proxy: "", currentMode: "direct"}; + } + + const status = response.data; + console.log("Proxy status from background:", status); + + // 返回当前模式 + return { + enable: status.enabled, + proxy: status.mode === "system" ? "system" : "", + currentMode: status.mode || "direct", // 使用 mode 来判断当前激活的代理 + }; } catch (error) { - console.warn(`Attempt ${i + 1} failed:`, error); - if (i === maxRetries - 1) { - throw error; + console.error("Error getting proxy status:", error); + return {enable: false, proxy: "", currentMode: "direct"}; + } + } + + // 获取所有代理配置 + async function getProxyConfigs() { + try { + const response = await sendMessageWithRetry({ + action: ProxyActionType.GET_PROXY_CONFIGS, + }); + + if (!response) { + console.log("No response from background script"); + return []; } - // 等待一小段时间后重试 - await new Promise(resolve => setTimeout(resolve, 500)); - } - } -} - -// 获取当前代理状态 -async function getCurrentProxy() { - try { - const response = await sendMessageWithRetry({ - action: ProxyActionType.GET_PROXY_STATUS - }); - - if (!response || !response.success) { - console.log('No valid response from background script'); - return { enable: false, proxy: '', currentMode: 'direct' }; - } - - const status = response.data; - console.log('Proxy status from background:', status); - - // 返回当前模式 - return { - enable: status.enabled, - proxy: status.mode === 'system' ? 'system' : '', - currentMode: status.mode || 'direct' // 使用 mode 来判断当前激活的代理 - }; - } catch (error) { - console.error('Error getting proxy status:', error); - return { enable: false, proxy: '', currentMode: 'direct' }; - } -} - -// 获取所有代理配置 -async function getProxyConfigs() { - try { - const response = await sendMessageWithRetry({ - action: ProxyActionType.GET_PROXY_CONFIGS - }); - - if (!response) { - console.log('No response from background script'); + if (!response.success) { + console.error("Error in response:", response.error); + return []; + } + return response.data || []; + } catch (error) { + console.error("Error getting proxy configs:", error); return []; } - if (!response.success) { - console.error('Error in response:', response.error); - return []; - } - return response.data || []; - } catch (error) { - console.error('Error getting proxy configs:', error); - return []; } -} -// 切换代理 -async function switchProxy(config) { - try { - console.log('Switching proxy:', config); - - // 根据配置类型构建正确的配置对象 - let proxyConfig; - if (config.proxyType === 'system') { - proxyConfig = { - id: 'system', - name: '[系统代理]', - proxyType: 'system', - enabled: true - }; - } else if (config.proxyType === 'direct') { - proxyConfig = { - id: 'direct', - name: '[直接连接]', - proxyType: 'direct', - enabled: false - }; - } else { - proxyConfig = { - ...config, - enabled: true - }; - } + // 切换代理 + async function switchProxy(config) { + try { + console.log("Switching proxy:", config); - // 发送配置更改消息 - await sendMessageWithRetry({ - action: ProxyActionType.SET_PROXY_CONFIG, - config: proxyConfig - }); - - await PanelManager.updatePanel(); - } catch (error) { - console.error('Error switching proxy:', error); - } -} - -// 清除代理 -async function clearProxy() { - try { - const response = await sendMessageWithRetry({ - action: ProxyActionType.SET_PROXY_CONFIG, - config: { - id: 'direct', - name: '[直接连接]', - proxyType: 'direct', - enabled: false + // 根据配置类型构建正确的配置对象 + let proxyConfig; + if (config.proxyType === "system") { + proxyConfig = { + id: "system", + name: "[系统代理]", + proxyType: "system", + enabled: true, + }; + } else if (config.proxyType === "direct") { + proxyConfig = { + id: "direct", + name: "[直接连接]", + proxyType: "direct", + enabled: false, + }; + } else { + proxyConfig = { + ...config, + enabled: true, + }; } - }); - - console.log('Clear proxy response:', response); - // 使用 PanelManager 的 updatePanel 方法 - await PanelManager.updatePanel(); - } catch (error) { - console.error('Error clearing proxy:', error); + + // 发送配置更改消息 + await sendMessageWithRetry({ + action: ProxyActionType.SET_PROXY_CONFIG, + config: proxyConfig, + }); + + await PanelManager.updatePanel(); + } catch (error) { + console.error("Error switching proxy:", error); + } } -} -// 修改 PanelManager -const PanelManager = { - panel: null, - messageListener: null, - _updating: false, - _updateQueue: Promise.resolve(), - _currentState: null, // 用于跟踪当前状态 - _lastUpdate: null, // 添加最后更新时间戳 - _lastState: null, - _pollingInterval: null, - isDragging: false, - startY: 0, - currentY: 0, - - init() { - // 确保 document.body 存在 - if (!document.body) { - console.log('Body not ready, waiting...'); - this.waitForBody(); - return; + // 清除代理 + async function clearProxy() { + try { + const response = await sendMessageWithRetry({ + action: ProxyActionType.SET_PROXY_CONFIG, + config: { + id: "direct", + name: "[直接连接]", + proxyType: "direct", + enabled: false, + }, + }); + + console.log("Clear proxy response:", response); + // 使用 PanelManager 的 updatePanel 方法 + await PanelManager.updatePanel(); + } catch (error) { + console.error("Error clearing proxy:", error); } + } - if (this.panel) { - console.log('Panel already exists, updating...'); - this.updatePanel(); - return; - } - - console.log('Creating new panel...'); - this.createPanel(); - }, + // 修改 PanelManager + const PanelManager = { + panel: null, + messageListener: null, + _updating: false, + _updateQueue: Promise.resolve(), + _currentState: null, // 用于跟踪当前状态 + _lastUpdate: null, // 添加最后更新时间戳 + _lastState: null, + _pollingInterval: null, + isDragging: false, + startY: 0, + currentY: 0, - // 添加等待 body 的方法 - waitForBody() { - if (document.body) { - this.init(); - return; - } + init() { + // 确保 document.body 存在 + if (!document.body) { + console.log("Body not ready, waiting..."); + this.waitForBody(); + return; + } - console.log('Setting up MutationObserver for body'); - const observer = new MutationObserver((mutations, obs) => { + if (this.panel) { + console.log("Panel already exists, updating..."); + this.updatePanel(); + return; + } + + console.log("Creating new panel..."); + this.createPanel(); + }, + + // 添加等待 body 的方法 + waitForBody() { if (document.body) { - console.log('Body found via observer'); - obs.disconnect(); this.init(); + return; } - }); - observer.observe(document.documentElement, { - childList: true, - subtree: true - }); - }, - - createPanel() { - if (!document.body) { - console.log('Body not available during panel creation'); - return; - } + console.log("Setting up MutationObserver for body"); + const observer = new MutationObserver((mutations, obs) => { + if (document.body) { + console.log("Body found via observer"); + obs.disconnect(); + this.init(); + } + }); - // 创建容器 - const container = document.createElement('div'); - container.id = 'yakit-proxy-panel'; - - // 创建 shadow DOM - const shadow = container.attachShadow({ mode: 'open' }); - - // 添加样式 - const style = document.createElement('style'); - style.textContent = ` + observer.observe(document.documentElement, { + childList: true, + subtree: true, + }); + }, + + createPanel() { + if (!document.body) { + console.log("Body not available during panel creation"); + return; + } + + // 创建容器 + const container = document.createElement("div"); + container.id = "yakit-proxy-panel"; + + // 创建 shadow DOM + const shadow = container.attachShadow({mode: "open"}); + + // 添加样式 + const style = document.createElement("style"); + style.textContent = ` .floating-panel { position: fixed; top: 30%; @@ -439,10 +446,10 @@ const PanelManager = { } `; - // 创建面板内容 - const panel = document.createElement('div'); - panel.className = 'floating-panel'; - panel.innerHTML = ` + // 创建面板内容 + const panel = document.createElement("div"); + panel.className = "floating-panel"; + panel.innerHTML = `