index.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. import Awesome from '../background/awesome.js'
  2. import MSG_TYPE from '../static/js/common.js';
  3. import Settings from './settings.js';
  4. import Statistics from '../background/statistics.js';
  5. import toolMap from '../background/tools.js';
  6. // 工具分类定义
  7. const TOOL_CATEGORIES = [
  8. { key: 'dev', name: '开发工具类', tools: ['json-format', 'json-diff', 'code-beautify', 'code-compress', 'postman', 'websocket', 'regexp','page-timing'] },
  9. { key: 'encode', name: '编解码转换类', tools: ['en-decode', 'trans-radix', 'timestamp', 'trans-color'] },
  10. { key: 'image', name: '图像处理类', tools: ['qr-code', 'image-base64', 'svg-converter', 'chart-maker', 'poster-maker' ,'screenshot', 'color-picker'] },
  11. { key: 'productivity', name: '效率工具类', tools: ['aiagent', 'sticky-notes', 'html2markdown', 'page-monkey'] },
  12. { key: 'calculator', name: '计算工具类', tools: ['crontab', 'loan-rate', 'password'] },
  13. { key: 'other', name: '其他工具', tools: [] }
  14. ];
  15. // Vue实例
  16. new Vue({
  17. el: '#marketContainer',
  18. data: {
  19. manifest: { version: '0.0.0' },
  20. searchKey: '',
  21. currentCategory: '',
  22. sortType: 'default',
  23. viewMode: 'list', // 默认网格视图
  24. categories: TOOL_CATEGORIES,
  25. favorites: new Set(),
  26. recentUsed: [],
  27. loading: true,
  28. originalTools: {}, // 保存原始工具数据
  29. currentView: 'all', // 当前视图类型(all/installed/favorites/recent)
  30. activeTools: {}, // 当前显示的工具列表
  31. installedCount: 0, // 已安装工具数量
  32. // 版本相关
  33. latestVersion: '', // 最新版本号
  34. needUpdate: false, // 是否需要更新
  35. // 设置相关
  36. showSettingsModal: false,
  37. defaultKey: 'Alt+Shift+J', // 默认快捷键
  38. countDown: 0, // 夜间模式倒计时
  39. selectedOpts: [], // 选中的选项
  40. menuDownloadCrx: false, // 菜单-插件下载
  41. menuFeHelperSeting: false, // 菜单-FeHelper设置
  42. isFirefox: false, // 是否Firefox浏览器
  43. // 打赏相关
  44. showDonateModal: false,
  45. donate: {
  46. text: '感谢你对FeHelper的认可和支持!',
  47. image: './donate.jpeg'
  48. },
  49. // 确认对话框
  50. confirmDialog: {
  51. show: false,
  52. title: '操作确认',
  53. message: '',
  54. callback: null,
  55. data: null
  56. },
  57. recentCount: 0,
  58. versionChecked: false,
  59. // 推荐卡片配置,后续可从服务端获取
  60. recommendationCards: [
  61. {
  62. toolKey: 'qr-code',
  63. icon: '📱',
  64. title: '二维码工具',
  65. desc: '快速生成和识别二维码,支持自定义样式',
  66. tag: '必装',
  67. tagClass: 'must-tag',
  68. isAd: false
  69. },
  70. {
  71. toolKey: 'chart-maker',
  72. icon: '📊',
  73. title: '图表制作工具',
  74. desc: '支持多种数据可视化图表,快速生成专业图表',
  75. tag: '最新',
  76. tagClass: 'new-tag',
  77. isAd: false
  78. },
  79. {
  80. toolKey: 'poster-maker',
  81. icon: '🖼️',
  82. title: '海报快速生成',
  83. desc: '快速生成和识别二维码,支持自定义样式',
  84. tag: '推荐',
  85. tagClass: 'recommend-tag',
  86. isAd: false
  87. },
  88. {
  89. icon: '🔔',
  90. title: '推广位',
  91. desc: '广告位招租,欢迎流量主联系,开放合作,流量主请到github联系',
  92. tag: '广告',
  93. tagClass: 'ad-tag',
  94. isAd: true,
  95. url: 'https://github.com/zxlie/FeHelper'
  96. }
  97. ],
  98. },
  99. async created() {
  100. await this.initData();
  101. this.recentCount = (await Statistics.getRecentUsedTools(10)).length;
  102. // 初始化后更新已安装工具数量
  103. this.updateInstalledCount();
  104. // 恢复用户的视图模式设置
  105. this.loadViewMode();
  106. // 加载设置项
  107. this.loadSettings();
  108. // 检查浏览器类型
  109. this.checkBrowserType();
  110. // 检查版本更新
  111. this.checkVersionUpdate();
  112. // 检查URL中是否有donate_from参数
  113. this.checkDonateParam();
  114. // 埋点:自动触发options
  115. chrome.runtime.sendMessage({
  116. type: 'fh-dynamic-any-thing',
  117. thing: 'statistics-tool-usage',
  118. params: {
  119. tool_name: 'options'
  120. }
  121. });
  122. },
  123. computed: {
  124. filteredTools() {
  125. if (this.loading) {
  126. return [];
  127. }
  128. // 获取当前工具列表
  129. let result = Object.values(this.activeTools).map(tool => ({
  130. ...tool,
  131. favorite: this.favorites.has(tool.key)
  132. }));
  133. // 搜索过滤
  134. if (this.searchKey) {
  135. const key = this.searchKey.toLowerCase();
  136. result = result.filter(tool =>
  137. tool.name.toLowerCase().includes(key) ||
  138. tool.tips.toLowerCase().includes(key)
  139. );
  140. }
  141. // 分类过滤,在所有视图下生效
  142. if (this.currentCategory) {
  143. const category = TOOL_CATEGORIES.find(c => c.key === this.currentCategory);
  144. const categoryTools = category ? category.tools : [];
  145. result = result.filter(tool => categoryTools.includes(tool.key));
  146. }
  147. // 排序
  148. switch (this.sortType) {
  149. case 'newest':
  150. result.sort((a, b) => (b.updateTime || 0) - (a.updateTime || 0));
  151. break;
  152. case 'hot':
  153. result.sort((a, b) => (b.updateTime || 0) - (a.updateTime || 0));
  154. break;
  155. default:
  156. const allTools = TOOL_CATEGORIES.reduce((acc, category) => {
  157. acc.push(...category.tools);
  158. return acc;
  159. }, []);
  160. result.sort((a, b) => {
  161. const indexA = allTools.indexOf(a.key);
  162. const indexB = allTools.indexOf(b.key);
  163. // 如果工具不在任何类别中,放到最后
  164. if (indexA === -1 && indexB === -1) {
  165. return a.key.localeCompare(b.key); // 字母顺序排序
  166. }
  167. if (indexA === -1) return 1;
  168. if (indexB === -1) return -1;
  169. return indexA - indexB;
  170. });
  171. }
  172. return result;
  173. }
  174. },
  175. methods: {
  176. async initData() {
  177. try {
  178. this.loading = true;
  179. // 获取manifest信息
  180. const manifest = await chrome.runtime.getManifest();
  181. this.manifest = manifest;
  182. // 从 Awesome.getAllTools 获取工具列表
  183. const tools = await Awesome.getAllTools();
  184. // 获取收藏数据
  185. const favorites = await this.getFavoritesData();
  186. this.favorites = new Set(favorites);
  187. // 获取最近使用数据
  188. const recentUsed = await this.getRecentUsedData();
  189. this.recentUsed = recentUsed;
  190. this.recentCount = recentUsed.length;
  191. // 获取已安装工具列表
  192. const installedTools = await Awesome.getInstalledTools();
  193. // 处理工具数据
  194. const processedTools = {};
  195. Object.entries(tools).forEach(([key, tool]) => {
  196. // 检查工具是否已安装
  197. const isInstalled = installedTools.hasOwnProperty(key);
  198. // 检查是否有右键菜单
  199. const hasMenu = tool.menu || false;
  200. processedTools[key] = {
  201. ...tool,
  202. key, // 添加key到工具对象中
  203. updateTime: Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000,
  204. installed: isInstalled, // 使用实时安装状态
  205. inContextMenu: hasMenu, // 使用实时菜单状态
  206. systemInstalled: tool.systemInstalled || false, // 是否系统预装
  207. favorite: this.favorites.has(key)
  208. };
  209. });
  210. this.originalTools = processedTools;
  211. // 初始化activeTools为所有工具
  212. this.activeTools = { ...processedTools };
  213. // 更新"其他工具"类别
  214. this.updateOtherCategory(Object.keys(processedTools));
  215. // 默认选中"全部分类"
  216. this.currentCategory = '';
  217. } catch (error) {
  218. console.error('初始化数据失败:', error);
  219. } finally {
  220. this.loading = false;
  221. }
  222. },
  223. // 更新"其他工具"类别,将未分类的工具添加到此类别
  224. updateOtherCategory(allToolKeys) {
  225. // 获取所有已分类的工具
  226. const categorizedTools = new Set();
  227. TOOL_CATEGORIES.forEach(category => {
  228. if (category.key !== 'other') {
  229. category.tools.forEach(tool => categorizedTools.add(tool));
  230. }
  231. });
  232. // 找出未分类的工具
  233. const uncategorizedTools = allToolKeys.filter(key => !categorizedTools.has(key));
  234. // 更新"其他工具"类别
  235. const otherCategory = TOOL_CATEGORIES.find(category => category.key === 'other');
  236. if (otherCategory) {
  237. otherCategory.tools = uncategorizedTools;
  238. }
  239. },
  240. // 检查版本更新
  241. async checkVersionUpdate() {
  242. try {
  243. // 获取已安装的版本号
  244. const currentVersion = this.manifest.version;
  245. // 尝试从本地存储获取最新版本信息,避免频繁请求
  246. const cachedData = await new Promise(resolve => {
  247. chrome.storage.local.get('fehelper_latest_version_data', data => {
  248. resolve(data.fehelper_latest_version_data || null);
  249. });
  250. });
  251. // 检查是否需要重新获取版本信息:
  252. // 1. 缓存不存在
  253. // 2. 缓存已过期(超过24小时)
  254. // 3. 缓存的当前版本与实际版本不同(说明插件已更新)
  255. const now = Date.now();
  256. const cacheExpired = !cachedData || !cachedData.timestamp || (now - cachedData.timestamp > 24 * 60 * 60 * 1000);
  257. const versionChanged = cachedData && cachedData.currentVersion !== currentVersion;
  258. this.versionChecked = !(cacheExpired || versionChanged);
  259. if (!this.versionChecked) {
  260. try {
  261. // 使用shields.io的JSON API获取最新版本号
  262. const response = await fetch('https://img.shields.io/chrome-web-store/v/pkgccpejnmalmdinmhkkfafefagiiiad.json');
  263. if (!response.ok) {
  264. throw new Error(`HTTP错误:${response.status}`);
  265. }
  266. this.versionChecked = true;
  267. const data = await response.json();
  268. // 提取版本号 - shields.io返回的数据中包含版本信息
  269. let latestVersion = '';
  270. if (data && data.value) {
  271. // 去掉版本号前的'v'字符(如果有)
  272. latestVersion = data.value.replace(/^v/, '');
  273. }
  274. // 比较版本号
  275. const needUpdate = this.compareVersions(currentVersion, latestVersion) < 0;
  276. // 保存到本地存储中
  277. await chrome.storage.local.set({
  278. 'fehelper_latest_version_data': {
  279. timestamp: now,
  280. currentVersion, // 保存当前检查时的版本号
  281. latestVersion,
  282. needUpdate
  283. }
  284. });
  285. this.latestVersion = latestVersion;
  286. this.needUpdate = needUpdate;
  287. } catch (fetchError) {
  288. // 获取失败时不显示更新按钮
  289. this.needUpdate = false;
  290. // 如果是版本变更导致的重新检查,但获取失败,则使用缓存数据
  291. if (versionChanged && cachedData) {
  292. this.latestVersion = cachedData.latestVersion || '';
  293. // 比较新的currentVersion和缓存的latestVersion
  294. this.needUpdate = this.compareVersions(currentVersion, cachedData.latestVersion) < 0;
  295. }
  296. }
  297. } else {
  298. // 使用缓存数据
  299. this.latestVersion = cachedData.latestVersion || '';
  300. this.needUpdate = cachedData.needUpdate || false;
  301. }
  302. } catch (error) {
  303. this.needUpdate = false; // 出错时不显示更新提示
  304. }
  305. },
  306. // 比较版本号:如果v1 < v2返回-1,v1 = v2返回0,v1 > v2返回1
  307. compareVersions(v1, v2) {
  308. // 将版本号拆分为数字数组
  309. const v1Parts = v1.split('.').map(Number);
  310. const v2Parts = v2.split('.').map(Number);
  311. // 计算两个版本号中较长的长度
  312. const maxLength = Math.max(v1Parts.length, v2Parts.length);
  313. // 比较每一部分
  314. for (let i = 0; i < maxLength; i++) {
  315. // 获取当前部分,如果不存在则视为0
  316. const part1 = v1Parts[i] || 0;
  317. const part2 = v2Parts[i] || 0;
  318. // 比较当前部分
  319. if (part1 < part2) return -1;
  320. if (part1 > part2) return 1;
  321. }
  322. // 所有部分都相等
  323. return 0;
  324. },
  325. // 打开Chrome商店页面
  326. openStorePage() {
  327. try {
  328. // 使用Chrome Extension API请求检查更新
  329. // Manifest V3中requestUpdateCheck返回Promise,结果是一个对象而不是数组
  330. chrome.runtime.requestUpdateCheck().then(result => {
  331. // 正确获取status和details,它们是result对象的属性
  332. this.handleUpdateStatus(result.status, result.details);
  333. }).catch(error => {
  334. this.handleUpdateError(error);
  335. });
  336. } catch (error) {
  337. this.handleUpdateError(error);
  338. }
  339. },
  340. // 处理更新状态
  341. handleUpdateStatus(status, details) {
  342. if (status === 'update_available') {
  343. // 显示更新通知
  344. this.showNotification({
  345. title: 'FeHelper 更新',
  346. message: '已发现新版本,正在更新...'
  347. });
  348. // 重新加载扩展以应用更新
  349. setTimeout(() => {
  350. chrome.runtime.reload();
  351. }, 1000);
  352. } else if (status === 'no_update') {
  353. // 如果没有可用更新,但用户点击了更新按钮
  354. this.showNotification({
  355. title: 'FeHelper 更新',
  356. message: '您的FeHelper已经是最新版本。'
  357. });
  358. } else {
  359. // 其他情况,如更新检查失败等
  360. // 备选方案:跳转到官方网站
  361. chrome.tabs.create({
  362. url: 'https://baidufe.com/fehelper'
  363. });
  364. this.showNotification({
  365. title: 'FeHelper 更新',
  366. message: '自动更新失败,请访问FeHelper官网手动获取最新版本。'
  367. });
  368. }
  369. },
  370. // 处理更新错误
  371. handleUpdateError(error) {
  372. // 出错时跳转到官方网站
  373. chrome.tabs.create({
  374. url: 'https://baidufe.com/fehelper'
  375. });
  376. this.showNotification({
  377. title: 'FeHelper 更新错误',
  378. message: '更新过程中出现错误,请手动检查更新。'
  379. });
  380. },
  381. // 显示通知的统一方法
  382. showNotification(options) {
  383. try {
  384. // 定义通知ID,方便后续关闭
  385. const notificationId = 'fehelper-update-notification';
  386. const simpleNotificationId = 'fehelper-simple-notification';
  387. // 直接尝试创建通知,不检查权限
  388. // Chrome扩展在manifest中已声明notifications权限,应该可以直接使用
  389. const notificationOptions = {
  390. type: 'basic',
  391. iconUrl: chrome.runtime.getURL('static/img/fe-48.png'),
  392. title: options.title || 'FeHelper',
  393. message: options.message || '',
  394. priority: 2,
  395. requireInteraction: false, // 改为false,因为我们会手动关闭
  396. silent: false // 播放音效
  397. };
  398. // 首先尝试直接创建通知
  399. chrome.notifications.create(notificationId, notificationOptions, (createdId) => {
  400. const error = chrome.runtime.lastError;
  401. if (error) {
  402. // 通知创建失败,尝试使用alert作为备选方案
  403. alert(`${options.title}: ${options.message}`);
  404. // 再尝试使用不同的选项创建通知
  405. const simpleOptions = {
  406. type: 'basic',
  407. iconUrl: chrome.runtime.getURL('static/img/fe-48.png'),
  408. title: options.title || 'FeHelper',
  409. message: options.message || ''
  410. };
  411. // 使用简化选项再次尝试
  412. chrome.notifications.create(simpleNotificationId, simpleOptions, (simpleId) => {
  413. if (chrome.runtime.lastError) {
  414. console.error('简化通知创建也失败:', chrome.runtime.lastError);
  415. } else {
  416. // 3秒后自动关闭简化通知
  417. setTimeout(() => {
  418. chrome.notifications.clear(simpleId);
  419. }, 3000);
  420. }
  421. });
  422. } else {
  423. // 3秒后自动关闭通知
  424. setTimeout(() => {
  425. chrome.notifications.clear(createdId);
  426. }, 3000);
  427. }
  428. });
  429. // 同时使用内置UI显示消息
  430. this.showInPageNotification(options);
  431. } catch (error) {
  432. // 降级为alert
  433. alert(`${options.title}: ${options.message}`);
  434. }
  435. },
  436. // 在页面内显示通知消息
  437. showInPageNotification(options) {
  438. try {
  439. // 创建一个通知元素
  440. const notificationEl = document.createElement('div');
  441. notificationEl.className = 'in-page-notification';
  442. notificationEl.innerHTML = `
  443. <div class="notification-content">
  444. <div class="notification-title">${options.title || 'FeHelper'}</div>
  445. <div class="notification-message">${options.message || ''}</div>
  446. </div>
  447. <button class="notification-close">×</button>
  448. `;
  449. // 添加样式
  450. const style = document.createElement('style');
  451. style.textContent = `
  452. .in-page-notification {
  453. position: fixed;
  454. bottom: 20px;
  455. right: 20px;
  456. background-color: #4285f4;
  457. color: white;
  458. padding: 15px;
  459. border-radius: 8px;
  460. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  461. z-index: 9999;
  462. display: flex;
  463. align-items: center;
  464. justify-content: space-between;
  465. min-width: 300px;
  466. animation: slideIn 0.3s ease-out;
  467. }
  468. .notification-content {
  469. flex: 1;
  470. }
  471. .notification-title {
  472. font-weight: bold;
  473. margin-bottom: 5px;
  474. }
  475. .notification-message {
  476. font-size: 14px;
  477. }
  478. .notification-close {
  479. background: none;
  480. border: none;
  481. color: white;
  482. font-size: 20px;
  483. cursor: pointer;
  484. margin-left: 10px;
  485. padding: 0 5px;
  486. }
  487. @keyframes slideIn {
  488. from { transform: translateX(100%); opacity: 0; }
  489. to { transform: translateX(0); opacity: 1; }
  490. }
  491. @keyframes slideOut {
  492. from { transform: translateX(0); opacity: 1; }
  493. to { transform: translateX(100%); opacity: 0; }
  494. }
  495. `;
  496. // 添加到页面
  497. document.head.appendChild(style);
  498. document.body.appendChild(notificationEl);
  499. // 点击关闭按钮移除通知
  500. const closeBtn = notificationEl.querySelector('.notification-close');
  501. if (closeBtn) {
  502. closeBtn.addEventListener('click', () => {
  503. notificationEl.style.animation = 'slideOut 0.3s ease-out forwards';
  504. notificationEl.addEventListener('animationend', () => {
  505. notificationEl.remove();
  506. });
  507. });
  508. }
  509. // 3秒后自动移除(从5秒改为3秒)
  510. setTimeout(() => {
  511. notificationEl.style.animation = 'slideOut 0.3s ease-out forwards';
  512. notificationEl.addEventListener('animationend', () => {
  513. notificationEl.remove();
  514. });
  515. }, 3000);
  516. } catch (error) {
  517. console.error('创建页内通知出错:', error);
  518. }
  519. },
  520. async getFavoritesData() {
  521. return new Promise((resolve) => {
  522. chrome.storage.local.get('favorites', (result) => {
  523. resolve(result.favorites || []);
  524. });
  525. });
  526. },
  527. async getRecentUsedData() {
  528. // 直接从Statistics模块获取最近使用的工具
  529. return await Statistics.getRecentUsedTools(10);
  530. },
  531. async saveFavorites() {
  532. try {
  533. await chrome.storage.local.set({
  534. favorites: Array.from(this.favorites)
  535. });
  536. // 更新工具的收藏状态
  537. Object.keys(this.originalTools).forEach(key => {
  538. this.originalTools[key].favorite = this.favorites.has(key);
  539. });
  540. } catch (error) {
  541. console.error('保存收藏失败:', error);
  542. }
  543. },
  544. handleSearch() {
  545. // 搜索时不重置视图类型,允许在已过滤的结果中搜索
  546. },
  547. handleCategoryChange(category) {
  548. // 切换到全部工具视图
  549. if (this.currentView !== 'all') {
  550. this.currentView = 'all';
  551. this.updateActiveTools('all');
  552. }
  553. this.currentCategory = category;
  554. this.searchKey = '';
  555. // 确保工具显示正确
  556. this.activeTools = { ...this.originalTools };
  557. },
  558. handleSort() {
  559. // 排序逻辑已在computed中实现
  560. },
  561. getCategoryCount(categoryKey) {
  562. const category = TOOL_CATEGORIES.find(c => c.key === categoryKey);
  563. const categoryTools = category ? category.tools : [];
  564. return categoryTools.length;
  565. },
  566. async getInstalledCount() {
  567. try {
  568. // 使用Awesome.getInstalledTools实时获取已安装工具数量
  569. const installedTools = await Awesome.getInstalledTools();
  570. return Object.keys(installedTools).length;
  571. } catch (error) {
  572. // 回退到本地数据
  573. return Object.values(this.originalTools).filter(tool =>
  574. tool.installed || tool.systemInstalled || false
  575. ).length;
  576. }
  577. },
  578. getFavoritesCount() {
  579. return this.favorites.size;
  580. },
  581. getToolCategory(toolKey) {
  582. for (const category of TOOL_CATEGORIES) {
  583. if (category.tools.includes(toolKey)) {
  584. return category.key;
  585. }
  586. }
  587. return 'other';
  588. },
  589. async showMyInstalled() {
  590. this.currentView = 'installed';
  591. this.currentCategory = '';
  592. this.searchKey = '';
  593. await this.updateActiveTools('installed');
  594. // 更新已安装工具数量
  595. await this.updateInstalledCount();
  596. },
  597. showMyFavorites() {
  598. this.currentView = 'favorites';
  599. this.currentCategory = '';
  600. this.searchKey = '';
  601. this.updateActiveTools('favorites');
  602. },
  603. // 重置工具列表到原始状态
  604. resetTools() {
  605. this.currentView = 'all';
  606. },
  607. // 安装工具
  608. async installTool(toolKey) {
  609. try {
  610. // 查找可能存在的按钮元素
  611. const btnElement = document.querySelector(`button[data-tool="${toolKey}"]`);
  612. let elProgress = null;
  613. // 如果是通过按钮点击调用的,获取进度条元素
  614. if (btnElement) {
  615. if (btnElement.getAttribute('data-undergoing') === '1') {
  616. return false;
  617. }
  618. btnElement.setAttribute('data-undergoing', '1');
  619. elProgress = btnElement.querySelector('span.x-progress');
  620. }
  621. // 显示安装进度
  622. let pt = 1;
  623. await Awesome.install(toolKey);
  624. // 只有当进度条元素存在时才更新文本内容
  625. if (elProgress) {
  626. elProgress.textContent = `(${pt}%)`;
  627. let ptInterval = setInterval(() => {
  628. elProgress.textContent = `(${pt}%)`;
  629. pt += Math.floor(Math.random() * 20);
  630. if(pt > 100) {
  631. clearInterval(ptInterval);
  632. elProgress.textContent = ``;
  633. // 在进度条完成后显示安装成功的通知
  634. this.showInPageNotification({
  635. message: `${this.originalTools[toolKey].name} 安装成功!`,
  636. type: 'success',
  637. duration: 3000
  638. });
  639. }
  640. }, 100);
  641. } else {
  642. // 如果没有进度条元素,直接显示通知
  643. this.showInPageNotification({
  644. message: `${this.originalTools[toolKey].name} 安装成功!`,
  645. type: 'success',
  646. duration: 3000
  647. });
  648. }
  649. // 更新原始数据和当前活动数据
  650. this.originalTools[toolKey].installed = true;
  651. if (this.activeTools[toolKey]) {
  652. this.activeTools[toolKey].installed = true;
  653. }
  654. // 更新已安装工具数量
  655. this.updateInstalledCount();
  656. // 如果按钮存在,更新其状态
  657. if (btnElement) {
  658. btnElement.setAttribute('data-undergoing', '0');
  659. }
  660. // 发送消息通知后台更新
  661. chrome.runtime.sendMessage({
  662. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  663. toolName: toolKey,
  664. action: 'install',
  665. showTips: true
  666. });
  667. } catch (error) {
  668. // 显示安装失败的通知
  669. this.showInPageNotification({
  670. message: `安装失败:${error.message || '未知错误'}`,
  671. type: 'error',
  672. duration: 5000
  673. });
  674. }
  675. },
  676. // 卸载工具
  677. async uninstallTool(toolKey) {
  678. try {
  679. // 使用自定义确认对话框而非浏览器原生的confirm
  680. this.showConfirm({
  681. title: '卸载确认',
  682. message: `确定要卸载"${this.originalTools[toolKey].name}"工具吗?`,
  683. callback: async (key) => {
  684. try {
  685. await chrome.runtime.sendMessage({
  686. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  687. toolName: key,
  688. action: 'offload',
  689. showTips: true
  690. });
  691. // 调用Awesome.offLoad卸载工具
  692. await Awesome.offLoad(key);
  693. // 更新原始数据和当前活动数据
  694. this.originalTools[key].installed = false;
  695. this.originalTools[key].inContextMenu = false;
  696. if (this.activeTools[key]) {
  697. this.activeTools[key].installed = false;
  698. this.activeTools[key].inContextMenu = false;
  699. }
  700. // 更新已安装工具数量
  701. this.updateInstalledCount();
  702. // 显示卸载成功的通知
  703. this.showInPageNotification({
  704. message: `${this.originalTools[key].name} 已成功卸载!`,
  705. type: 'success',
  706. duration: 3000
  707. });
  708. } catch (error) {
  709. // 显示卸载失败的通知
  710. this.showInPageNotification({
  711. message: `卸载失败:${error.message || '未知错误'}`,
  712. type: 'error',
  713. duration: 5000
  714. });
  715. }
  716. },
  717. data: toolKey
  718. });
  719. } catch (error) {
  720. console.error('准备卸载过程中出错:', error);
  721. }
  722. },
  723. // 切换右键菜单
  724. async toggleContextMenu(toolKey) {
  725. try {
  726. const tool = this.originalTools[toolKey];
  727. const newState = !tool.inContextMenu;
  728. // 更新菜单状态
  729. await Awesome.menuMgr(toolKey, newState ? 'install' : 'offload');
  730. // 更新原始数据和当前活动数据
  731. tool.inContextMenu = newState;
  732. if (this.activeTools[toolKey]) {
  733. this.activeTools[toolKey].inContextMenu = newState;
  734. }
  735. // 发送消息通知后台更新右键菜单
  736. chrome.runtime.sendMessage({
  737. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  738. action: `menu-${newState ? 'install' : 'offload'}`,
  739. showTips: false,
  740. menuOnly: true
  741. });
  742. } catch (error) {
  743. console.error('切换右键菜单失败:', error);
  744. }
  745. },
  746. // 切换收藏状态
  747. async toggleFavorite(toolKey) {
  748. try {
  749. if (this.favorites.has(toolKey)) {
  750. this.favorites.delete(toolKey);
  751. // 更新原始数据和当前活动数据
  752. this.originalTools[toolKey].favorite = false;
  753. if (this.activeTools[toolKey]) {
  754. this.activeTools[toolKey].favorite = false;
  755. }
  756. } else {
  757. this.favorites.add(toolKey);
  758. // 更新原始数据和当前活动数据
  759. this.originalTools[toolKey].favorite = true;
  760. if (this.activeTools[toolKey]) {
  761. this.activeTools[toolKey].favorite = true;
  762. }
  763. }
  764. await this.saveFavorites();
  765. // 如果是在收藏视图,需要更新视图
  766. if (this.currentView === 'favorites') {
  767. this.updateActiveTools('favorites');
  768. }
  769. } catch (error) {
  770. console.error('切换收藏状态失败:', error);
  771. }
  772. },
  773. async updateActiveTools(view) {
  774. if (this.loading || Object.keys(this.originalTools).length === 0) {
  775. return;
  776. }
  777. switch (view) {
  778. case 'installed':
  779. // 使用Awesome.getInstalledTools实时获取已安装工具
  780. try {
  781. const installedTools = await Awesome.getInstalledTools();
  782. // 合并installedTools与originalTools的数据
  783. this.activeTools = Object.fromEntries(
  784. Object.entries(this.originalTools).filter(([key]) =>
  785. installedTools.hasOwnProperty(key)
  786. )
  787. );
  788. } catch (error) {
  789. // 回退到本地数据
  790. this.activeTools = Object.fromEntries(
  791. Object.entries(this.originalTools).filter(([_, tool]) =>
  792. tool.installed || tool.systemInstalled || false
  793. )
  794. );
  795. }
  796. break;
  797. case 'favorites':
  798. this.activeTools = Object.fromEntries(
  799. Object.entries(this.originalTools).filter(([key]) => this.favorites.has(key))
  800. );
  801. break;
  802. case 'recent':
  803. // 切换recent时,recentUsed已在showRecentUsed中实时拉取
  804. this.activeTools = Object.fromEntries(
  805. Object.entries(this.originalTools).filter(([key]) => this.recentUsed.includes(key))
  806. );
  807. break;
  808. case 'all':
  809. default:
  810. this.activeTools = { ...this.originalTools };
  811. // 分类过滤在computed属性中处理
  812. break;
  813. }
  814. },
  815. // 新增更新已安装工具数量的方法
  816. async updateInstalledCount() {
  817. this.installedCount = await this.getInstalledCount();
  818. },
  819. // 加载用户保存的视图模式
  820. async loadViewMode() {
  821. try {
  822. const result = await new Promise(resolve => {
  823. chrome.storage.local.get('fehelper_view_mode', result => {
  824. resolve(result.fehelper_view_mode);
  825. });
  826. });
  827. if (result) {
  828. this.viewMode = result;
  829. }
  830. } catch (error) {
  831. console.error('加载视图模式失败:', error);
  832. }
  833. },
  834. // 保存用户的视图模式选择
  835. async saveViewMode(mode) {
  836. try {
  837. this.viewMode = mode;
  838. await chrome.storage.local.set({
  839. 'fehelper_view_mode': mode
  840. });
  841. } catch (error) {
  842. console.error('保存视图模式失败:', error);
  843. }
  844. },
  845. // 加载设置项
  846. async loadSettings() {
  847. try {
  848. Settings.getOptions(async (opts) => {
  849. let selectedOpts = [];
  850. Object.keys(opts).forEach(key => {
  851. if(String(opts[key]) === 'true') {
  852. selectedOpts.push(key);
  853. }
  854. });
  855. this.selectedOpts = selectedOpts;
  856. // 加载右键菜单设置
  857. this.menuDownloadCrx = await Awesome.menuMgr('download-crx', 'get') === '1';
  858. this.menuFeHelperSeting = await Awesome.menuMgr('fehelper-setting', 'get') !== '0';
  859. // 获取快捷键
  860. chrome.commands.getAll((commands) => {
  861. for (let command of commands) {
  862. if (command.name === '_execute_action') {
  863. this.defaultKey = command.shortcut || 'Alt+Shift+J';
  864. break;
  865. }
  866. }
  867. });
  868. });
  869. } catch (error) {
  870. console.error('加载设置项失败:', error);
  871. }
  872. },
  873. // 检查浏览器类型
  874. checkBrowserType() {
  875. try {
  876. this.isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  877. } catch (error) {
  878. this.isFirefox = false;
  879. }
  880. },
  881. // 显示设置模态框
  882. showSettings() {
  883. this.showSettingsModal = true;
  884. },
  885. // 关闭设置模态框
  886. closeSettings() {
  887. this.showSettingsModal = false;
  888. },
  889. // 显示打赏模态框
  890. openDonateModal() {
  891. this.showDonateModal = true;
  892. },
  893. // 关闭打赏模态框
  894. closeDonateModal() {
  895. this.showDonateModal = false;
  896. },
  897. // 显示确认对话框
  898. showConfirm(options) {
  899. this.confirmDialog = {
  900. show: true,
  901. title: options.title || '操作确认',
  902. message: options.message || '确定要执行此操作吗?',
  903. callback: options.callback || null,
  904. data: options.data || null
  905. };
  906. },
  907. // 确认操作
  908. confirmAction() {
  909. if (this.confirmDialog.callback) {
  910. this.confirmDialog.callback(this.confirmDialog.data);
  911. }
  912. this.confirmDialog.show = false;
  913. },
  914. // 取消确认
  915. cancelConfirm() {
  916. this.confirmDialog.show = false;
  917. },
  918. // 保存设置
  919. async saveSettings() {
  920. try {
  921. // 构建设置对象
  922. let opts = {};
  923. ['OPT_ITEM_CONTEXTMENUS', 'FORBID_OPEN_IN_NEW_TAB', 'CONTENT_SCRIPT_ALLOW_ALL_FRAMES',
  924. 'JSON_PAGE_FORMAT', 'AUTO_DARK_MODE', 'ALWAYS_DARK_MODE'].forEach(key => {
  925. opts[key] = this.selectedOpts.includes(key).toString();
  926. });
  927. // 保存设置 - 直接传递对象,settings.js已增加对对象类型的支持
  928. Settings.setOptions(opts, async () => {
  929. try {
  930. // 处理右键菜单
  931. const crxAction = this.menuDownloadCrx ? 'install' : 'offload';
  932. const settingAction = this.menuFeHelperSeting ? 'install' : 'offload';
  933. await Promise.all([
  934. Awesome.menuMgr('download-crx', crxAction),
  935. Awesome.menuMgr('fehelper-setting', settingAction)
  936. ]);
  937. // 通知后台更新右键菜单
  938. chrome.runtime.sendMessage({
  939. type: MSG_TYPE.DYNAMIC_TOOL_INSTALL_OR_OFFLOAD,
  940. action: 'menu-change',
  941. menuOnly: true
  942. });
  943. // 关闭弹窗
  944. this.closeSettings();
  945. // 显示提示
  946. this.showNotification({
  947. title: 'FeHelper 设置',
  948. message: '设置已保存!'
  949. });
  950. } catch (innerError) {
  951. this.showNotification({
  952. title: 'FeHelper 设置错误',
  953. message: '保存菜单设置失败: ' + innerError.message
  954. });
  955. }
  956. });
  957. } catch (error) {
  958. this.showNotification({
  959. title: 'FeHelper 设置错误',
  960. message: '保存设置失败: ' + error.message
  961. });
  962. }
  963. },
  964. // 设置快捷键
  965. setShortcuts() {
  966. chrome.tabs.create({
  967. url: 'chrome://extensions/shortcuts'
  968. });
  969. },
  970. // 体验夜间模式
  971. turnLight(event) {
  972. event.preventDefault();
  973. // 获取body元素
  974. const body = document.body;
  975. // 切换夜间模式
  976. if (body.classList.contains('dark-mode')) {
  977. body.classList.remove('dark-mode');
  978. } else {
  979. body.classList.add('dark-mode');
  980. // 设置倒计时
  981. this.countDown = 10;
  982. // 启动倒计时
  983. const timer = setInterval(() => {
  984. this.countDown--;
  985. if (this.countDown <= 0) {
  986. clearInterval(timer);
  987. body.classList.remove('dark-mode');
  988. }
  989. }, 1000);
  990. }
  991. },
  992. // 检查URL中的donate_from参数并显示打赏弹窗
  993. checkDonateParam() {
  994. try {
  995. const urlParams = new URLSearchParams(window.location.search);
  996. const donateFrom = urlParams.get('donate_from');
  997. if (donateFrom) {
  998. // 记录打赏来源
  999. chrome.storage.local.set({
  1000. 'fehelper_donate_from': donateFrom,
  1001. 'fehelper_donate_time': Date.now()
  1002. });
  1003. // 等待工具数据加载完成
  1004. this.$nextTick(() => {
  1005. // 在所有工具中查找匹配项
  1006. let matchedTool = null;
  1007. // 首先尝试直接匹配工具key
  1008. if (this.originalTools && this.originalTools[donateFrom]) {
  1009. matchedTool = this.originalTools[donateFrom];
  1010. } else if (this.originalTools) {
  1011. // 如果没有直接匹配,尝试在所有工具中查找部分匹配
  1012. for (const [key, tool] of Object.entries(this.originalTools)) {
  1013. if (key.includes(donateFrom) || donateFrom.includes(key) ||
  1014. (tool.name && tool.name.includes(donateFrom)) ||
  1015. (donateFrom && donateFrom.includes(tool.name))) {
  1016. matchedTool = tool;
  1017. break;
  1018. }
  1019. }
  1020. }
  1021. // 更新打赏文案
  1022. if (matchedTool) {
  1023. this.donate.text = `看起来【${matchedTool.name}】工具帮助到了你,感谢你的认可!`;
  1024. } else {
  1025. // 没有匹配到特定工具,使用通用文案
  1026. this.donate.text = `感谢你对FeHelper的认可和支持!`;
  1027. }
  1028. // 显示打赏弹窗
  1029. this.showDonateModal = true;
  1030. });
  1031. // 埋点:自动触发options
  1032. chrome.runtime.sendMessage({
  1033. type: 'fh-dynamic-any-thing',
  1034. thing: 'statistics-tool-usage',
  1035. params: {
  1036. tool_name: 'donate'
  1037. }
  1038. });
  1039. }
  1040. } catch (error) {
  1041. console.error('处理打赏参数时出错:', error);
  1042. }
  1043. },
  1044. // 补充 getRecentCount,保证模板调用不报错,且数据源唯一
  1045. async getRecentCount() {
  1046. const recent = await Statistics.getRecentUsedTools(10);
  1047. return recent.length;
  1048. },
  1049. async showRecentUsed() {
  1050. this.currentView = 'recent';
  1051. this.currentCategory = '';
  1052. this.searchKey = '';
  1053. // recentUsed已在initData和getRecentUsedData中维护,activeTools会自动刷新
  1054. },
  1055. handleRecommendClick(card) {
  1056. if (card.isAd && card.url) {
  1057. window.open(card.url, '_blank');
  1058. } else if (card.toolKey) {
  1059. this.installTool(card.toolKey);
  1060. }
  1061. },
  1062. },
  1063. watch: {
  1064. // 监听currentView变化
  1065. currentView: {
  1066. immediate: true,
  1067. handler(newView) {
  1068. this.updateActiveTools(newView);
  1069. }
  1070. },
  1071. // 监听currentCategory变化
  1072. currentCategory: {
  1073. handler(newCategory) {
  1074. // 保证在视图模式之外的分类切换也能正确显示
  1075. if (this.currentView === 'all') {
  1076. this.activeTools = { ...this.originalTools };
  1077. }
  1078. // 重置搜索条件
  1079. if (this.searchKey) {
  1080. this.searchKey = '';
  1081. }
  1082. }
  1083. },
  1084. },
  1085. });
  1086. // 添加滚动事件监听
  1087. window.addEventListener('scroll', () => {
  1088. const header = document.querySelector('.market-header');
  1089. const sidebar = document.querySelector('.market-sidebar');
  1090. if (window.scrollY > 10) {
  1091. header.classList.add('scrolled');
  1092. sidebar && sidebar.classList.add('scrolled');
  1093. } else {
  1094. header.classList.remove('scrolled');
  1095. sidebar && sidebar.classList.remove('scrolled');
  1096. }
  1097. });
  1098. // 页面加载后自动采集
  1099. if (window.chrome && chrome.runtime && chrome.runtime.sendMessage) {
  1100. Awesome.collectAndSendClientInfo();
  1101. }