feat: 更新背景脚本和内容脚本,添加录制控制消息处理,优化录制状态检查逻辑,新增消息常量

This commit is contained in:
雨霖铃
2026-01-30 23:08:49 +08:00
parent 0ff33cbeb3
commit 88a612f9cf
7 changed files with 201 additions and 105 deletions
+53 -15
View File
@@ -1,27 +1,65 @@
export default defineBackground(() => {
console.log('Hello background!', { id: browser.runtime.id });
chrome.runtime.onMessage.addListener(async (msg, sender, sendResponse) => {
if (msg.type === 'CREATE_OFFSCREEN') {
const exists = await chrome.offscreen.hasDocument();
if (!exists) {
await chrome.offscreen.createDocument({
url: 'offscreen.html',
reasons: ['DISPLAY_MEDIA', 'USER_MEDIA', 'BLOBS', 'AUDIO_PLAYBACK'],
justification: 'rrweb record & replay',
});
console.log('[bg] offscreen created');
browser.runtime.onInstalled.addListener(async ({ reason }) => {
if (reason === 'install') {
// 第一次安装扩展时触发
console.log('Extension installed for the first time');
} else if (reason === 'update') {
// 扩展更新时触发
console.log('Extension updated to a new version');
}
// 给所有已打开的标签页注入 content script
for (const tab of await browser.tabs.query({})) {
if (tab.url?.match(/(chrome|chrome-extension):\/\//gi) || !tab.id) {
continue;
}
// 注入 content script
const res = browser.scripting.executeScript({
target: { tabId: tab.id },
files: ['/content-scripts/content.js'],
});
console.log('Content script injected on installed/updated:', res);
}
});
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
// 处理来自其他部分的消息
console.log('[bg] message received:', msg, sender.tab);
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const currentTab = tabs[0];
console.log('[bg] 真正活跃的页面标题是:', currentTab?.title);
sendResponse({ ok: true, title: currentTab?.title });
});
if (msg.type === 'CREATE_OFFSCREEN') {
console.log('[bg] offscreen created');
sendResponse({ ok: true });
}
if (msg.type === 'DOWNLOAD') {
console.log('[bg] DOWNLOAD received');
chrome.downloads.download({
url: msg.dataUrl,
filename: `rrweb-${Date.now()}.json`,
saveAs: true,
});
sendResponse({ ok: true });
}
return true;
});
async function sendToActiveTab(message: {
type: string;
data?: any;
activeTabId?: number;
[key: string]: any;
}) {
let activeTabs = await browser.tabs.query({
active: true,
currentWindow: true,
});
let activeTab = activeTabs[0];
const sendTo = message.activeTabId || activeTab.id;
await browser.tabs.sendMessage(sendTo!, message);
}
});