fix Firefox proxy set

This commit is contained in:
go0p
2026-08-06 15:11:35 +08:00
committed by go0p
parent 19410e9f96
commit ff01c7c7b4
2 changed files with 121 additions and 88 deletions
+2 -2
View File
@@ -361,9 +361,9 @@ body {
}
.active-item {
background-color: #F28B44 !important;
background-color: var(--yakit-primary) !important;
color: white !important;
font-weight: 500;
font-weight: bold;
transition: background-color 0.2s ease-in-out !important;
}
+111 -78
View File
@@ -1,43 +1,48 @@
import React, {useEffect, useState} from 'react';
import {Menu} from 'antd';
import {DisconnectOutlined, SettingOutlined, PlusOutlined, CheckOutlined} from '@ant-design/icons';
import {browser,} from 'wxt/browser';
import type {MenuProps} from 'antd';
import type {ProxyConfig} from '@/types/proxy';
import {ContentActionType, ProxyActionType} from '@/types/action';
import { getAllProxyConfigs, getCurrentProxy } from '@/utils/storage';
import React, {useEffect, useState} from "react";
import {Menu} from "antd";
import {
DisconnectOutlined,
SettingOutlined,
PlusOutlined,
CheckOutlined,
} from "@ant-design/icons";
import {browser} from "wxt/browser";
import type {MenuProps} from "antd";
import type {ProxyConfig} from "@/types/proxy";
import {ContentActionType, ProxyActionType} from "@/types/action";
import {getAllProxyConfigs, getCurrentProxy} from "@/utils/storage";
import './index.css';
import "./index.css";
// YAK 图标 URL
const YAK_ICON_URL = browser.runtime.getURL('/yak.svg');
const YAK_ICON_URL = browser.runtime.getURL("/yak.svg");
// 固定的代理模式
const FIXED_MODES = [
{
key: 'direct',
name: '[直接连接]',
key: "direct",
name: "[直接连接]",
icon: <DisconnectOutlined/>,
color: '#666',
color: "#666",
config: {
id: 'direct',
name: '[直接连接]',
proxyType: 'direct',
enabled: false
}
id: "direct",
name: "[直接连接]",
proxyType: "direct",
enabled: false,
},
},
{
key: 'system',
name: '[系统代理]',
key: "system",
name: "[系统代理]",
icon: <SettingOutlined/>,
color: '#666',
color: "#666",
config: {
id: 'system',
name: '[系统代理]',
proxyType: 'system',
enabled: false
}
}
id: "system",
name: "[系统代理]",
proxyType: "system",
enabled: false,
},
},
];
interface CustomProxy {
@@ -50,14 +55,19 @@ interface CustomProxy {
export const ProxySwitch: React.FC = () => {
const [initialized, setInitialized] = useState<boolean>(false);
const [currentMode, setCurrentMode] = useState<string>('');
const [currentMode, setCurrentMode] = useState<string>("");
const [customProxies, setCustomProxies] = useState<CustomProxy[]>([]);
const [isLoading, setIsLoading] = useState<boolean>(false);
// 监听存储变化
useEffect(() => {
const handleMessage = (message: any) => {
if (message.action === ContentActionType.PROXY_CONFIGS_UPDATED && message.source !== 'proxy_switch') {
if (
message.action === ContentActionType.PROXY_CONFIGS_UPDATED &&
message.source !== "proxy_switch"
) {
console.log("proxy_switch 收到代理配置更新消息", message);
loadCustomProxies();
loadProxyStatus();
}
@@ -84,8 +94,9 @@ export const ProxySwitch: React.FC = () => {
try {
// 先尝试从后台脚本获取当前代理状态
const response = await browser.runtime.sendMessage({
action: ProxyActionType.GET_PROXY_STATUS
action: ProxyActionType.GET_PROXY_STATUS,
});
console.log("proxy_switch 获取当前代理状态", response);
if (response && response.success) {
const activeMode = response.data.mode;
@@ -98,11 +109,11 @@ export const ProxySwitch: React.FC = () => {
if (currentProxy) {
setCurrentMode(currentProxy.id);
} else {
setCurrentMode('direct');
setCurrentMode("direct");
}
} catch (error) {
console.error('Error loading proxy status:', error);
setCurrentMode('direct');
console.error("Error loading proxy status:", error);
setCurrentMode("direct");
}
};
@@ -114,60 +125,65 @@ export const ProxySwitch: React.FC = () => {
// 处理代理配置
const proxies = configs
.filter((proxy: ProxyConfig) => !['direct', 'system'].includes(proxy.id))
.map((proxy: ProxyConfig): CustomProxy => ({
.filter(
(proxy: ProxyConfig) => !["direct", "system"].includes(proxy.id)
)
.map(
(proxy: ProxyConfig): CustomProxy => ({
key: proxy.id,
name: proxy.name,
color: '#1890ff',
color: "#1890ff",
config: proxy,
enabled: proxy.enabled
}));
enabled: proxy.enabled,
})
);
setCustomProxies(proxies);
console.log("proxy_switch proxies", proxies);
// 查找并设置已启用的代理
const enabledProxy = configs.find((proxy: ProxyConfig) => proxy.enabled);
if (enabledProxy) {
console.log("proxy_switch enabledProxy", enabledProxy);
setCurrentMode(enabledProxy.id);
}
} catch (error) {
console.error('Error loading custom proxies:', error);
console.error("Error loading custom proxies:", error);
setCustomProxies([]);
}
};
// 处理代理模式变更
const handleModeChange = async (mode: string) => {
if (mode === 'setting') {
if (mode === "setting") {
// 打开设置页面
await browser.runtime.openOptionsPage?.();
return;
}
if (mode === 'add') {
if (mode === "add") {
// 打开添加代理表单
try {
const [activeTab] = await browser.tabs.query({
active: true,
currentWindow: true
currentWindow: true,
});
const optionsUrl = browser.runtime.getURL('/options.html');
const optionsUrl = browser.runtime.getURL("/options.html");
if (activeTab?.url === optionsUrl) {
browser.tabs.sendMessage(activeTab.id!, {
action: ContentActionType.TRIGGER_ADD_PROXY
action: ContentActionType.TRIGGER_ADD_PROXY,
});
} else {
await browser.tabs.create({
url: optionsUrl
url: optionsUrl,
});
}
} catch (error) {
console.error('Failed to get current tab:', error);
console.error("Failed to get current tab:", error);
}
return;
}
console.log("proxy_switch 处理代理模式变更", mode);
// 如果当前已经是选中的模式,不做任何操作
if (mode === currentMode) return;
@@ -180,16 +196,20 @@ export const ProxySwitch: React.FC = () => {
// 发送切换代理请求
const response = await browser.runtime.sendMessage({
action: ProxyActionType.SWITCH_PROXY,
mode
mode,
source: "proxy_switch",
});
if (!response || !response.success) {
// 如果失败,恢复原状态
console.error('Failed to switch proxy mode');
console.error("Failed to switch proxy mode");
await loadProxyStatus(); // 重新加载正确的状态
} else {
// 成功时刷新代理列表状态
await loadCustomProxies();
setTimeout(() => {
setCurrentMode((preMode) => {
return mode === preMode ? preMode : mode;
});
}, 20);
}
} catch (error) {
console.error(`Error switching to proxy mode ${mode}:`, error);
@@ -201,64 +221,76 @@ export const ProxySwitch: React.FC = () => {
// 构建菜单项
const buildMenuItems = () => {
const items: MenuProps['items'] = [
...FIXED_MODES.map(mode => ({
const items: MenuProps["items"] = [
...FIXED_MODES.map((mode) => ({
key: mode.key,
label: mode.name,
icon: mode.icon,
className: `${currentMode === mode.key ? 'active-item' : ''} menu-id-${mode.key}`,
className: `${currentMode === mode.key ? "active-item" : ""} menu-id-${
mode.key
}`,
})),
{type: 'divider'}
{type: "divider"},
];
// 添加自定义代理
if (customProxies.length > 0) {
items.push(
...customProxies.map(proxy => {
...customProxies.map((proxy) => {
// 构建提示信息:显示代理协议、主机和端口
const tooltipText = proxy.config.proxyType === 'fixed_servers' && proxy.config.host && proxy.config.port
? `${proxy.config.scheme || 'http'}://${proxy.config.host}:${proxy.config.port}`
: proxy.config.proxyType === 'pac_script'
? 'PAC脚本代理'
: proxy.config.proxyType === 'auto_detect'
? '自动检测代理'
: '';
const tooltipText =
proxy.config.proxyType === "fixed_servers" &&
proxy.config.host &&
proxy.config.port
? `${proxy.config.scheme || "http"}://${proxy.config.host}:${
proxy.config.port
}`
: proxy.config.proxyType === "pac_script"
? "PAC脚本代理"
: proxy.config.proxyType === "auto_detect"
? "自动检测代理"
: "";
// Firefox 兼容性:确保 active-item 类始终应用正确
const isActive = currentMode === proxy.key;
return {
key: proxy.key,
label: proxy.name,
icon: <img
icon: (
<img
src={YAK_ICON_URL}
alt="YAK"
style={{
width: 20,
height: 20,
filter: currentMode === proxy.key ? 'brightness(0) invert(1)' : 'none',
transition: 'filter 0.2s ease-in-out'
filter: isActive ? "brightness(0) invert(1)" : "none",
transition: "filter 0.2s ease-in-out",
}}
/>,
className: `${currentMode === proxy.key ? 'active-item' : ''} menu-id-${proxy.key}`,
/>
),
className: `${isActive ? "active-item" : ""} menu-id-${proxy.key}`,
title: tooltipText, // 添加悬停提示
};
})
);
items.push({type: 'divider'});
items.push({type: "divider"});
}
// 添加设置选项
items.push({
key: 'setting',
label: '代理设置',
icon: <SettingOutlined />,
className: 'menu-id-setting',
key: "setting",
label: "代理设置",
icon: <SettingOutlined/>,
className: "menu-id-setting",
});
// 添加新建代理选项
items.push({
key: 'add',
label: '添加代理',
icon: <PlusOutlined />,
className: 'menu-id-add',
key: "add",
label: "添加代理",
icon: <PlusOutlined/>,
className: "menu-id-add",
});
return items;
@@ -271,6 +303,7 @@ export const ProxySwitch: React.FC = () => {
selectedKeys={[currentMode]}
items={buildMenuItems()}
onClick={({key}) => handleModeChange(key)}
key={`proxy-menu-${currentMode}`}
/>
{isLoading && <div className="loading-overlay">...</div>}
</div>