import type { BackgroundCommand, BackgroundResponse, CrawlStateResponse } from '../types'; import { cancelAutoclose, cancelCrawl, cancelCrawlWhenWindowRemoved, cancelStaleCrawlWhenWindowMissing, dismissCrawl, resumeCrawl, startCrawl, } from './crawlTask'; import { getCrawlTaskState } from './taskState'; /** * 扩展安装完成时的初始化入口,当前仅保留日志方便调试生命周期。 */ export async function handleInstalled(): Promise { console.log('[background] installed'); } /** * 浏览器启动并加载扩展时的初始化入口,当前仅保留日志方便调试生命周期。 */ export async function handleStartup(): Promise { console.log('[background] startup'); await cancelStaleCrawlWhenWindowMissing(); } /** * 监听窗口关闭事件;如果关闭的是爬取窗口,就把当前任务标记为取消。 */ export async function handleWindowRemoved(windowId: number): Promise { console.log('[background] window removed', windowId); await cancelCrawlWhenWindowRemoved(windowId); } /** * 根据 popup/content 发来的 action 分发到对应的后台处理函数。 */ export async function handleBackgroundCommand( message: BackgroundCommand, ): Promise { switch (message.action) { case 'START_CRAWL': return startCrawl(message.payload.platformId); case 'GET_CRAWL_STATE': await cancelStaleCrawlWhenWindowMissing(); return { ok: true, data: await getCrawlTaskState() }; case 'CANCEL_CRAWL': return cancelCrawl(); case 'RESUME_CRAWL': return resumeCrawl(); case 'CANCEL_AUTOCLOSE': return cancelAutoclose(); case 'DISMISS_CRAWL': return dismissCrawl(); default: return { ok: false, error: '未知的后台指令' }; } }