4850c92365
* feat(formRecognizer): 添加表单识别功能及相关组件 添加表单识别功能,包括以下内容: 1. 在路由配置中添加表单识别页面 2. 实现表单识别页面和侧边栏面板 3. 添加表单数据生成工具类 4. 实现与内容脚本的通信机制 5. 添加faker-js依赖用于生成测试数据 6. 支持不同入口点(popup/sidepanel)的组件渲染 * refactor(消息通信): 重构消息通信机制并集中管理消息协议 将分散的消息协议和通信逻辑集中到 utils/messages.ts 中 移除旧的 messages.tsx 文件并更新相关引用 添加消息动作枚举和类型定义,提高类型安全性 优化内容脚本注入失败时的处理逻辑 * feat(QR码): 添加粘贴图片功能并优化上传组件 添加全局粘贴事件监听,支持从剪贴板直接粘贴二维码图片进行解析。重构上传组件为独立组件QrCodeUploader,包含拖拽上传、预览、进度显示和错误处理功能。优化页面样式和用户体验。 - 在QrCodePage添加粘贴事件监听 - 创建QrCodeUploader组件整合上传功能 - 更新测试用例格式 - 调整多个页面的背景色样式 * feat(表单识别): 新增表单识别页面功能与模板管理 - 添加表单识别页面样式配置 - 实现表单字段扫描与展示功能 - 新增数据模板管理工具类 - 添加数据验证工具类 - 扩展表单识别页面功能,包括操作历史记录 - 支持模板的导入导出功能 - 优化表单填充操作的用户体验 * feat(消息系统): 添加标签页刷新功能 在消息系统中新增 RELOAD_TAB 动作类型和 tabId 字段,用于处理标签页刷新请求 修改 StorageCleanerPage 使用后台脚本发送刷新请求,确保弹窗关闭后仍能执行 在 background.ts 中添加标签页刷新处理逻辑,包括错误处理和响应返回 * refactor(theme): 重构主题颜色和样式配置 - 更新主题颜色以满足 WCAG AA 可访问性标准 - 提取全局样式配置到统一变量 - 使用语义化颜色变量替换硬编码值 - 为输入框样式创建统一配置 * feat: add URL entry management components and QR code generation feature - Introduced `UrlEntryItem` and `UrlEntryList` components for displaying and managing URL entries. - Added `UrlToQrCodeSection` component for generating QR codes from URLs with download and copy functionality. - Implemented `AutoRefreshToggle`, `CleaningResult`, `DomainHeader`, `ErrorDisplay`, `OptionItem`, and `StorageOptionsGrid` components for enhanced user interface in storage cleaning. - Created custom hooks `useStorageCleaner` and `useStorageState` for managing storage-related states and preferences. - Added utility hook `useUrlPreferences` for handling URL entry preferences. * feat: 新增时间戳转换器和相关组件,优化时间戳页面功能 * Refactor message handling and storage cleaning logic * feat: 添加 GitHub Actions CI/CD 工作流,支持自动化构建与发布
419 lines
12 KiB
TypeScript
419 lines
12 KiB
TypeScript
import type { StorageCleanerOptions, CleaningResult, StorageCleanResult } from '@/types/storage';
|
|
|
|
const RESTRICTED_PROTOCOLS = [
|
|
'chrome:',
|
|
'chrome-extension:',
|
|
'about:',
|
|
'edge:',
|
|
'view-source:',
|
|
'file:',
|
|
'data:',
|
|
] as const;
|
|
|
|
export async function getCurrentTab() {
|
|
// For popup pages, we need to get the active tab from the browser window that triggered the popup.
|
|
// We should ONLY care about the currently active tab in the last focused window.
|
|
// If it's a restricted URL, we return it anyway and let the caller handle the error display.
|
|
|
|
const [tab] = await chrome.tabs.query({
|
|
active: true,
|
|
lastFocusedWindow: true,
|
|
});
|
|
|
|
if (tab) {
|
|
return tab;
|
|
}
|
|
|
|
// Fallback for cases where lastFocusedWindow might not work as expected (e.g. certain sidepanel scenarios)
|
|
const [fallbackTab] = await chrome.tabs.query({
|
|
active: true,
|
|
currentWindow: true,
|
|
});
|
|
|
|
return fallbackTab;
|
|
}
|
|
|
|
export function isRestrictedUrl(url?: string): boolean {
|
|
if (!url) return true;
|
|
return RESTRICTED_PROTOCOLS.some((p) => url.startsWith(p));
|
|
}
|
|
|
|
export async function getCookieSize(url: string): Promise<number> {
|
|
try {
|
|
const cookies = await chrome.cookies.getAll({ url });
|
|
// 估算:名称 + 值 + 域名 + 路径 的长度
|
|
return cookies.reduce(
|
|
(acc, c) =>
|
|
acc + c.name.length + c.value.length + (c.domain?.length || 0) + (c.path?.length || 0),
|
|
0,
|
|
);
|
|
} catch (error) {
|
|
console.error('Failed to get cookie size:', error);
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
export async function getLocalStorageSize(tabId: number): Promise<number> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: () => {
|
|
try {
|
|
return Object.entries(localStorage).reduce((acc, [k, v]) => acc + k.length + v.length, 0);
|
|
} catch {
|
|
return 0;
|
|
}
|
|
},
|
|
});
|
|
return (result?.result as number) || 0;
|
|
} catch (error) {
|
|
console.error('Failed to get LocalStorage size:', error);
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
export async function getSessionStorageSize(tabId: number): Promise<number> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: () => {
|
|
try {
|
|
return Object.entries(sessionStorage).reduce(
|
|
(acc, [k, v]) => acc + k.length + v.length,
|
|
0,
|
|
);
|
|
} catch {
|
|
return 0;
|
|
}
|
|
},
|
|
});
|
|
return (result?.result as number) || 0;
|
|
} catch (error) {
|
|
console.error('Failed to get SessionStorage size:', error);
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
export async function getIndexedDBSize(tabId: number): Promise<number> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: async () => {
|
|
try {
|
|
// 注意:navigator.storage.estimate() 返回的是整个 Origin 的估算值
|
|
// 包含 IndexedDB, CacheStorage, ServiceWorker 注册等
|
|
if (navigator.storage && navigator.storage.estimate) {
|
|
const estimate = await navigator.storage.estimate();
|
|
return estimate.usage || 0;
|
|
}
|
|
return 0;
|
|
} catch {
|
|
return 0;
|
|
}
|
|
},
|
|
});
|
|
return (result?.result as number) || 0;
|
|
} catch (error) {
|
|
console.error('Failed to get IndexedDB size:', error);
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
export async function getCacheStorageSize(tabId: number): Promise<number> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: async () => {
|
|
try {
|
|
if ('caches' in window) {
|
|
const keys = await caches.keys();
|
|
return keys.length; // 对于 CacheStorage,我们先返回缓存库的数量
|
|
}
|
|
return 0;
|
|
} catch {
|
|
return 0;
|
|
}
|
|
},
|
|
});
|
|
// 由于获取具体字节数较慢,这里返回的是缓存条目的数量标识,UI 上可以特殊处理
|
|
return (result?.result as number) || 0;
|
|
} catch (error) {
|
|
console.error('Failed to get CacheStorage size:', error);
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
export async function getServiceWorkerCount(tabId: number): Promise<number> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: async () => {
|
|
try {
|
|
if ('serviceWorker' in navigator) {
|
|
const regs = await navigator.serviceWorker.getRegistrations();
|
|
return regs.length;
|
|
}
|
|
return 0;
|
|
} catch {
|
|
return 0;
|
|
}
|
|
},
|
|
});
|
|
return (result?.result as number) || 0;
|
|
} catch (error) {
|
|
console.error('Failed to get ServiceWorker count:', error);
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
export function formatSize(bytes: number): string {
|
|
if (bytes === 0) return '0 B';
|
|
if (bytes < 1024) return `${bytes} B`; // 处理小于 1KB 的情况
|
|
const k = 1024;
|
|
const sizes = ['B', 'KB', 'MB', 'GB'];
|
|
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
|
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
|
}
|
|
|
|
export async function clearCookies(url: string): Promise<StorageCleanResult> {
|
|
try {
|
|
const cookies = await chrome.cookies.getAll({ url });
|
|
for (const cookie of cookies) {
|
|
const protocol = cookie.secure ? 'https:' : 'http:';
|
|
const cookieUrl = `${protocol}//${cookie.domain}${cookie.path}`;
|
|
await chrome.cookies.remove({
|
|
url: cookieUrl,
|
|
name: cookie.name,
|
|
storeId: cookie.storeId,
|
|
});
|
|
}
|
|
return { success: true, count: cookies.length };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
}
|
|
|
|
export async function injectClearLocalStorage(tabId: number): Promise<StorageCleanResult> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: () => {
|
|
const count = localStorage.length;
|
|
localStorage.clear();
|
|
return { count };
|
|
},
|
|
});
|
|
if (result?.result && typeof result.result === 'object' && 'count' in result.result) {
|
|
return { success: true, count: result.result.count };
|
|
}
|
|
return { success: false, error: 'No result returned' };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
}
|
|
|
|
export async function injectClearSessionStorage(tabId: number): Promise<StorageCleanResult> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: () => {
|
|
const count = sessionStorage.length;
|
|
sessionStorage.clear();
|
|
return { count };
|
|
},
|
|
});
|
|
if (result?.result && typeof result.result === 'object' && 'count' in result.result) {
|
|
return { success: true, count: result.result.count };
|
|
}
|
|
return { success: false, error: 'No result returned' };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
}
|
|
|
|
export async function injectClearIndexedDB(tabId: number): Promise<StorageCleanResult> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: async () => {
|
|
if (typeof indexedDB.databases === 'function') {
|
|
const databases = await indexedDB.databases();
|
|
let count = 0;
|
|
for (const db of databases) {
|
|
if (db.name) {
|
|
const dbName = db.name as string;
|
|
try {
|
|
await new Promise<void>((resolve, reject) => {
|
|
const deleteReq = indexedDB.deleteDatabase(dbName);
|
|
const timeout = setTimeout(() => {
|
|
console.warn('IndexedDB delete timeout:', dbName);
|
|
resolve(); // Timeout, move to next
|
|
}, 5000);
|
|
|
|
deleteReq.onblocked = () => {
|
|
console.warn('IndexedDB delete blocked:', dbName);
|
|
clearTimeout(timeout);
|
|
resolve(); // Blocked, move to next
|
|
};
|
|
deleteReq.onsuccess = () => {
|
|
clearTimeout(timeout);
|
|
resolve();
|
|
};
|
|
deleteReq.onerror = () => {
|
|
clearTimeout(timeout);
|
|
reject(new Error(`Failed to delete ${dbName}`));
|
|
};
|
|
});
|
|
count++;
|
|
} catch (e) {
|
|
console.error('Delete DB error:', e);
|
|
}
|
|
}
|
|
}
|
|
return { count };
|
|
}
|
|
return { error: 'databases_api_unavailable' };
|
|
},
|
|
});
|
|
if (result?.result && typeof result.result === 'object') {
|
|
if ('error' in result.result) {
|
|
return { success: false, error: String(result.result.error) };
|
|
}
|
|
if ('count' in result.result) {
|
|
return { success: true, count: result.result.count };
|
|
}
|
|
}
|
|
return { success: false, error: 'No result returned' };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
}
|
|
|
|
export async function injectClearCacheStorage(tabId: number): Promise<StorageCleanResult> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: async () => {
|
|
if ('caches' in window) {
|
|
const cacheNames = await caches.keys();
|
|
for (const name of cacheNames) {
|
|
await caches.delete(name);
|
|
}
|
|
return { count: cacheNames.length };
|
|
}
|
|
return { count: 0 };
|
|
},
|
|
});
|
|
if (result?.result && typeof result.result === 'object' && 'count' in result.result) {
|
|
return { success: true, count: result.result.count };
|
|
}
|
|
return { success: false, error: 'No result returned' };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
}
|
|
|
|
export async function injectUnregisterServiceWorkers(tabId: number): Promise<StorageCleanResult> {
|
|
try {
|
|
const [result] = await chrome.scripting.executeScript({
|
|
target: { tabId },
|
|
func: async () => {
|
|
if ('serviceWorker' in navigator) {
|
|
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
for (const registration of registrations) {
|
|
await registration.unregister();
|
|
}
|
|
return { count: registrations.length };
|
|
}
|
|
return { count: 0 };
|
|
},
|
|
});
|
|
if (result?.result && typeof result.result === 'object' && 'count' in result.result) {
|
|
return { success: true, count: result.result.count };
|
|
}
|
|
return { success: false, error: 'No result returned' };
|
|
} catch (error) {
|
|
return { success: false, error: String(error) };
|
|
}
|
|
}
|
|
|
|
export async function clearStorage(
|
|
tabId: number,
|
|
url: string,
|
|
options: StorageCleanerOptions,
|
|
): Promise<CleaningResult> {
|
|
const result: CleaningResult = { success: true };
|
|
|
|
if (options.localStorage) {
|
|
result.localStorage = await injectClearLocalStorage(tabId);
|
|
}
|
|
|
|
if (options.sessionStorage) {
|
|
result.sessionStorage = await injectClearSessionStorage(tabId);
|
|
}
|
|
|
|
if (options.indexedDB) {
|
|
result.indexedDB = await injectClearIndexedDB(tabId);
|
|
}
|
|
|
|
if (options.cookies) {
|
|
result.cookies = await clearCookies(url);
|
|
}
|
|
|
|
if (options.cacheStorage) {
|
|
result.cacheStorage = await injectClearCacheStorage(tabId);
|
|
}
|
|
|
|
if (options.serviceWorkers) {
|
|
result.serviceWorkers = await injectUnregisterServiceWorkers(tabId);
|
|
}
|
|
|
|
// Check if any operation failed
|
|
const failures = Object.values(result).filter(
|
|
(r): r is StorageCleanResult => r?.success === false,
|
|
);
|
|
|
|
if (failures.length > 0) {
|
|
result.success = false;
|
|
result.error = '部分清理失败';
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
export function formatCleaningResult(result: CleaningResult): string {
|
|
const parts: string[] = [];
|
|
|
|
if (result.localStorage?.success) {
|
|
parts.push(`${result.localStorage.count} 个 localStorage`);
|
|
}
|
|
if (result.sessionStorage?.success) {
|
|
parts.push(`${result.sessionStorage.count} 个 sessionStorage`);
|
|
}
|
|
if (result.indexedDB?.success) {
|
|
parts.push(`${result.indexedDB.count} 个 IndexedDB`);
|
|
}
|
|
if (result.cookies?.success) {
|
|
parts.push(`${result.cookies.count} 个 Cookies`);
|
|
}
|
|
if (result.cacheStorage?.success) {
|
|
parts.push(`${result.cacheStorage.count} 个 Cache`);
|
|
}
|
|
if (result.serviceWorkers?.success) {
|
|
parts.push(`${result.serviceWorkers.count} 个 Service Workers`);
|
|
}
|
|
|
|
if (parts.length === 0) {
|
|
return '该页面没有可清理的存储数据';
|
|
}
|
|
|
|
return `清理了 ${parts.join(', ')}`;
|
|
}
|
|
|
|
export function isEmptyResult(result: CleaningResult): boolean {
|
|
const values = Object.values(result).filter(
|
|
(r): r is StorageCleanResult => r?.success === true && r.count > 0,
|
|
);
|
|
return values.length === 0;
|
|
}
|