feat(background): 添加录制状态持久化和Tab切换处理
- 实现录制状态存储到本地storage,包括isRecording、recordingTabId、events和startTime - 添加loadRecorderState和saveRecorderState函数用于状态管理 - 监听Tab切换事件,当切换离开录制Tab时发出警告并通知popup - 监听Tab关闭事件,自动停止录制并清理状态 - 添加录制状态同步检查,确保content script状态一致 - 在开始录制前检查是否已在录制状态,避免重复录制 - 添加错误处理返回详细错误信息 - 优化回放HTML样式和脚本加载方式 - 添加Tab切换消息通信协议支持
This commit is contained in:
@@ -76,7 +76,7 @@ export function TimestampExecution(): JSX.Element {
|
|||||||
<Stack direction="row" spacing={2} justifyContent="center" flexWrap="wrap">
|
<Stack direction="row" spacing={2} justifyContent="center" flexWrap="wrap">
|
||||||
<Button
|
<Button
|
||||||
variant="contained"
|
variant="contained"
|
||||||
color="secondary"
|
color="primary"
|
||||||
onClick={toggleUnit}
|
onClick={toggleUnit}
|
||||||
aria-label={unitButtonLabel}
|
aria-label={unitButtonLabel}
|
||||||
title={unitButtonLabel}
|
title={unitButtonLabel}
|
||||||
|
|||||||
+140
-32
@@ -4,16 +4,49 @@ import { downloadHtmlInBackground } from '@/utils/recordUtils.tsx';
|
|||||||
import { sendMessage, onMessage } from '@/utils/messages';
|
import { sendMessage, onMessage } from '@/utils/messages';
|
||||||
import { getActiveTabId } from '@/utils/tabUtils';
|
import { getActiveTabId } from '@/utils/tabUtils';
|
||||||
|
|
||||||
const events: unknown[] = [];
|
interface RecorderState {
|
||||||
|
isRecording: boolean;
|
||||||
|
recordingTabId: number | undefined;
|
||||||
|
events: unknown[];
|
||||||
|
startTime: number | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const STORAGE_KEY = 'recorder_state';
|
||||||
|
|
||||||
|
// 从 storage 恢复录制状态
|
||||||
|
async function loadRecorderState(): Promise<RecorderState> {
|
||||||
|
try {
|
||||||
|
const result = await browser.storage.local.get(STORAGE_KEY);
|
||||||
|
return (result[STORAGE_KEY] as RecorderState) || {
|
||||||
|
isRecording: false,
|
||||||
|
recordingTabId: undefined,
|
||||||
|
events: [],
|
||||||
|
startTime: undefined,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[background] Failed to load recorder state:', err);
|
||||||
|
return { isRecording: false, recordingTabId: undefined, events: [], startTime: undefined };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存录制状态到 storage
|
||||||
|
async function saveRecorderState(state: Partial<RecorderState>) {
|
||||||
|
try {
|
||||||
|
const currentState = await loadRecorderState();
|
||||||
|
await browser.storage.local.set({
|
||||||
|
[STORAGE_KEY]: { ...currentState, ...state },
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[background] Failed to save recorder state:', err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export default defineBackground(() => {
|
export default defineBackground(() => {
|
||||||
// 监听扩展安装或更新事件
|
// 监听扩展安装或更新事件
|
||||||
browser.runtime.onInstalled.addListener(async ({ reason }) => {
|
browser.runtime.onInstalled.addListener(async ({ reason }) => {
|
||||||
if (reason === 'install') {
|
if (reason === 'install') {
|
||||||
// 第一次安装扩展时触发
|
|
||||||
console.log('Extension installed for the first time');
|
console.log('Extension installed for the first time');
|
||||||
} else if (reason === 'update') {
|
} else if (reason === 'update') {
|
||||||
// 扩展更新时触发
|
|
||||||
console.log('Extension updated to a new version');
|
console.log('Extension updated to a new version');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -23,7 +56,6 @@ export default defineBackground(() => {
|
|||||||
// 过滤不合法或受限制的 URL
|
// 过滤不合法或受限制的 URL
|
||||||
const targetTabs = tabs.filter((tab) => {
|
const targetTabs = tabs.filter((tab) => {
|
||||||
if (!tab.id || !tab.url) return false;
|
if (!tab.id || !tab.url) return false;
|
||||||
// 过滤掉浏览器内部页面和不支持注入的协议
|
|
||||||
const restrictedProtocols = [
|
const restrictedProtocols = [
|
||||||
'chrome:',
|
'chrome:',
|
||||||
'chrome-extension:',
|
'chrome-extension:',
|
||||||
@@ -51,71 +83,147 @@ export default defineBackground(() => {
|
|||||||
console.log(
|
console.log(
|
||||||
`Successfully injected content script into ${successCount}/${targetTabs.length} tabs.`,
|
`Successfully injected content script into ${successCount}/${targetTabs.length} tabs.`,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// 扩展安装/更新时重置录制状态
|
||||||
|
await saveRecorderState({ isRecording: false, recordingTabId: undefined, events: [], startTime: undefined });
|
||||||
});
|
});
|
||||||
|
|
||||||
chrome.tabs.onActivated.addListener((activeInfo) => {
|
// 监听 Tab 切换 - 如果正在录制且切换到其他 Tab,发出警告
|
||||||
console.log('当前活跃的 Tab ID:', activeInfo.tabId);
|
chrome.tabs.onActivated.addListener(async (activeInfo) => {
|
||||||
|
const state = await loadRecorderState();
|
||||||
|
if (state.isRecording && state.recordingTabId !== activeInfo.tabId) {
|
||||||
|
console.warn('[background] 录制中切换到其他 Tab,当前 Tab:', activeInfo.tabId, '录制 Tab:', state.recordingTabId);
|
||||||
|
// 可选:发送通知给 popup 更新 UI 提示用户
|
||||||
|
await sendMessage('popup:tab-changed', { currentTabId: activeInfo.tabId, recordingTabId: state.recordingTabId });
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
chrome.tabs.onUpdated.addListener((tabId) => {
|
chrome.tabs.onUpdated.addListener((tabId) => {
|
||||||
console.log('加载完成的 Tab ID:', tabId);
|
console.log('加载完成的 Tab ID:', tabId);
|
||||||
});
|
});
|
||||||
|
|
||||||
onMessage('popup:check-status', async (message) => {
|
// 监听 Tab 关闭 - 如果关闭的是录制中的 Tab,自动停止录制
|
||||||
console.log(`[background] popup:check-status: ${message}`);
|
chrome.tabs.onRemoved.addListener(async (tabId) => {
|
||||||
const obj = {
|
const state = await loadRecorderState();
|
||||||
active: false,
|
if (state.isRecording && state.recordingTabId === tabId) {
|
||||||
startTime: -1,
|
console.warn('[background] 录制中的 Tab 已关闭,自动停止录制');
|
||||||
};
|
// 这里可以调用停止逻辑或通知 popup
|
||||||
|
await sendMessage('popup:stopped', undefined);
|
||||||
try {
|
await saveRecorderState({ isRecording: false, recordingTabId: undefined, startTime: undefined });
|
||||||
const tabId = await getActiveTabId();
|
|
||||||
const result = await sendMessage('content:check-status', undefined, tabId);
|
|
||||||
console.log(`[background]111${result}`);
|
|
||||||
obj.active = result;
|
|
||||||
obj.startTime = new Date().getTime();
|
|
||||||
} catch (err) {
|
|
||||||
console.error(`[background-err]${err}`);
|
|
||||||
}
|
}
|
||||||
return obj;
|
});
|
||||||
|
|
||||||
|
onMessage('popup:check-status', async () => {
|
||||||
|
console.log('[background] popup:check-status');
|
||||||
|
const state = await loadRecorderState();
|
||||||
|
|
||||||
|
// 如果正在录制,额外检查 content script 的实际状态
|
||||||
|
if (state.isRecording && state.recordingTabId) {
|
||||||
|
try {
|
||||||
|
const result = await sendMessage('content:check-status', undefined, state.recordingTabId);
|
||||||
|
console.log('[background] content check-status result:', result);
|
||||||
|
// 如果 content script 返回 false,说明状态不同步,需要重置
|
||||||
|
if (!result) {
|
||||||
|
await saveRecorderState({ isRecording: false, recordingTabId: undefined, startTime: undefined });
|
||||||
|
return { active: false, startTime: -1 };
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[background-err] check-status failed:', err);
|
||||||
|
// Content script 可能已被移除(如页面刷新),重置状态
|
||||||
|
await saveRecorderState({ isRecording: false, recordingTabId: undefined, startTime: undefined });
|
||||||
|
return { active: false, startTime: -1 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { active: state.isRecording, startTime: state.startTime ?? -1 };
|
||||||
});
|
});
|
||||||
|
|
||||||
onMessage('popup:start', async () => {
|
onMessage('popup:start', async () => {
|
||||||
console.log('[bg] startRecording received');
|
console.log('[bg] startRecording received');
|
||||||
try {
|
try {
|
||||||
|
// 检查是否已经在录制
|
||||||
|
const currentState = await loadRecorderState();
|
||||||
|
if (currentState.isRecording) {
|
||||||
|
console.warn('[bg] 已经在录制中,无法开始新的录制');
|
||||||
|
return { ok: false, error: 'Already recording' };
|
||||||
|
}
|
||||||
|
|
||||||
const tabId = await getActiveTabId();
|
const tabId = await getActiveTabId();
|
||||||
const response = await sendMessage('content:start-recording', undefined, tabId);
|
const response = await sendMessage('content:start-recording', undefined, tabId);
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
|
// 保存录制状态到 storage
|
||||||
|
await saveRecorderState({
|
||||||
|
isRecording: true,
|
||||||
|
recordingTabId: tabId,
|
||||||
|
events: [], // 清空旧事件
|
||||||
|
startTime: Date.now(),
|
||||||
|
});
|
||||||
await sendMessage('popup:started', undefined);
|
await sendMessage('popup:started', undefined);
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
return { ok: false };
|
return { ok: false, error: response.error };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to start recording in content script', error);
|
console.error('Failed to start recording in content script', error);
|
||||||
return { ok: false };
|
return { ok: false, error: String(error) };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
onMessage('popup:stop', async () => {
|
onMessage('popup:stop', async () => {
|
||||||
console.log('[bg] stopRecording received');
|
console.log('[bg] stopRecording received');
|
||||||
try {
|
try {
|
||||||
const tabId = await getActiveTabId();
|
const state = await loadRecorderState();
|
||||||
const response = await sendMessage('content:stop-recording', undefined, tabId);
|
|
||||||
|
if (!state.isRecording) {
|
||||||
|
console.warn('[bg] 当前不在录制状态');
|
||||||
|
return { ok: false, error: 'Not recording' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const currentTabId = await getActiveTabId();
|
||||||
|
|
||||||
|
// Tab 一致性检查 - 允许一定程度的灵活性
|
||||||
|
if (state.recordingTabId !== currentTabId) {
|
||||||
|
console.warn(
|
||||||
|
`[bg] Tab 不一致:录制 Tab=${state.recordingTabId}, 当前 Tab=${currentTabId}`,
|
||||||
|
);
|
||||||
|
// 仍然尝试在录制 Tab 上停止(如果该 Tab 还存在)
|
||||||
|
// 如果需要在当前 Tab 停止,可以移除这个条件判断
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetTabId = state.recordingTabId ?? currentTabId;
|
||||||
|
const response = await sendMessage('content:stop-recording', undefined, targetTabId);
|
||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
|
// 下载回放文件
|
||||||
|
downloadHtmlInBackground(state.events);
|
||||||
|
|
||||||
|
// 清空状态
|
||||||
|
await saveRecorderState({
|
||||||
|
isRecording: false,
|
||||||
|
recordingTabId: undefined,
|
||||||
|
events: [],
|
||||||
|
startTime: undefined,
|
||||||
|
});
|
||||||
|
|
||||||
await sendMessage('popup:stopped', undefined);
|
await sendMessage('popup:stopped', undefined);
|
||||||
downloadHtmlInBackground(events);
|
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
return { ok: false };
|
return { ok: false, error: 'Failed to stop recording in content script' };
|
||||||
} catch (error: unknown) {
|
} catch (error: unknown) {
|
||||||
console.error('Failed to stop recording in content script', error);
|
console.error('Failed to stop recording in content script', error);
|
||||||
return { ok: false };
|
return { ok: false, error: String(error) };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
onMessage('content:save-tracke-events', (eventsList) => {
|
onMessage('content:save-tracke-events', async (event) => {
|
||||||
console.log('[bg] saveTrackeEvents received:', eventsList);
|
const state = await loadRecorderState();
|
||||||
events.push(eventsList);
|
if (!state.isRecording) {
|
||||||
|
console.warn('[bg] 收到事件但当前不在录制状态,丢弃事件');
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将新事件追加到现有事件列表
|
||||||
|
const updatedEvents = [...state.events, event];
|
||||||
|
await saveRecorderState({ events: updatedEvents });
|
||||||
return true;
|
return true;
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -43,13 +43,18 @@ const RecordeReplayPage = () => {
|
|||||||
const toggleRecording = async () => {
|
const toggleRecording = async () => {
|
||||||
try {
|
try {
|
||||||
if (isRecording) {
|
if (isRecording) {
|
||||||
await sendMessage('popup:stop', undefined);
|
const result = await sendMessage('popup:stop', undefined);
|
||||||
|
if (!result?.ok) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
await sendMessage('popup:start', undefined);
|
const result = await sendMessage('popup:start', undefined);
|
||||||
|
if (!result?.ok) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error toggling recording:', error);
|
console.error('Error toggling recording:', error);
|
||||||
setStatus(AppState.READ);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+4
-2
@@ -9,6 +9,7 @@ export const messages = {
|
|||||||
to: {
|
to: {
|
||||||
stopped: 'popup:stopped',
|
stopped: 'popup:stopped',
|
||||||
started: 'popup:started',
|
started: 'popup:started',
|
||||||
|
tabChanged: 'popup:tab-changed',
|
||||||
},
|
},
|
||||||
checkStatus: 'popup:check-status',
|
checkStatus: 'popup:check-status',
|
||||||
ready: 'popup:ready',
|
ready: 'popup:ready',
|
||||||
@@ -33,10 +34,11 @@ export const messages = {
|
|||||||
|
|
||||||
interface ProtocolMap {
|
interface ProtocolMap {
|
||||||
// --- Popup 相关 ---
|
// --- Popup 相关 ---
|
||||||
'popup:start': () => { ok: boolean };
|
'popup:start': () => { ok: boolean; error?: string };
|
||||||
'popup:stop': () => { ok: boolean };
|
'popup:stop': () => { ok: boolean; error?: string };
|
||||||
'popup:started': () => void;
|
'popup:started': () => void;
|
||||||
'popup:stopped': () => void;
|
'popup:stopped': () => void;
|
||||||
|
'popup:tab-changed': (data: { currentTabId: number; recordingTabId: number | undefined }) => void;
|
||||||
'popup:check-status': () => { active: boolean; startTime?: number };
|
'popup:check-status': () => { active: boolean; startTime?: number };
|
||||||
'popup:ready': () => void;
|
'popup:ready': () => void;
|
||||||
|
|
||||||
|
|||||||
+9
-12
@@ -1,7 +1,7 @@
|
|||||||
export const downloadHtmlInBackground = (events: unknown[]) => {
|
export const downloadHtmlInBackground = (events: unknown[]) => {
|
||||||
if (!events || events.length === 0) return;
|
if (!events || events.length === 0) return;
|
||||||
|
|
||||||
// 安全转义 (保持之前的修复)
|
// 安全转义
|
||||||
const safeEventsString = JSON.stringify(events)
|
const safeEventsString = JSON.stringify(events)
|
||||||
.replace(/\\/g, '\\\\')
|
.replace(/\\/g, '\\\\')
|
||||||
.replace(/`/g, '\\`')
|
.replace(/`/g, '\\`')
|
||||||
@@ -14,18 +14,23 @@ export const downloadHtmlInBackground = (events: unknown[]) => {
|
|||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
<title>RRWeb 回放</title>
|
<title>RRWeb 回放</title>
|
||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/rrweb-player@latest/dist/style.css" />
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/rrweb-player@latest/dist/style.css" />
|
||||||
|
<style>
|
||||||
|
body { margin: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; background: #f0f2f5; }
|
||||||
|
#player { width: 100%; max-width: 1024px; }
|
||||||
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body style="margin: 0; display: flex; justify-content: center; align-items: center; height: 100vh; background: #f0f2f5;">
|
<body>
|
||||||
<div id="player"></div>
|
<div id="player"></div>
|
||||||
|
|
||||||
|
<!-- 使用 UMD 版本,rrwebPlayer 会作为全局变量 -->
|
||||||
<script src="https://cdn.jsdelivr.net/npm/rrweb-player@latest/dist/index.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/rrweb-player@latest/dist/index.js"></script>
|
||||||
|
|
||||||
<script type="module">
|
<script type="module">
|
||||||
import { getReplayConsolePlugin } from 'https://esm.sh/@rrweb/rrweb-plugin-console-replay?bundle';
|
import { getReplayConsolePlugin } from 'https://esm.sh/@rrweb/rrweb-plugin-console-replay?bundle';
|
||||||
import rrwebPlayer from 'rrweb-player';
|
|
||||||
|
|
||||||
const events = JSON.parse(\`${safeEventsString}\`);
|
const events = JSON.parse(\`${safeEventsString}\`);
|
||||||
|
|
||||||
|
// rrwebPlayer 作为全局变量可用
|
||||||
new rrwebPlayer({
|
new rrwebPlayer({
|
||||||
target: document.getElementById('player'),
|
target: document.getElementById('player'),
|
||||||
props: {
|
props: {
|
||||||
@@ -34,15 +39,7 @@ export const downloadHtmlInBackground = (events: unknown[]) => {
|
|||||||
height: 576,
|
height: 576,
|
||||||
autoPlay: true,
|
autoPlay: true,
|
||||||
showController: true,
|
showController: true,
|
||||||
|
|
||||||
// --- 👇 关键修复:添加下面这行 ---
|
|
||||||
// 这会告诉 rrweb 关闭严格的 iframe 沙盒限制
|
|
||||||
// 从而消除 "Blocked script execution" 错误
|
|
||||||
// @ts-ignore
|
|
||||||
UNSAFE_replayCanvas: true,
|
UNSAFE_replayCanvas: true,
|
||||||
// ------------------------------
|
|
||||||
|
|
||||||
// @ts-ignore
|
|
||||||
plugins: [
|
plugins: [
|
||||||
getReplayConsolePlugin({
|
getReplayConsolePlugin({
|
||||||
level: ['info', 'log', 'warn', 'error'],
|
level: ['info', 'log', 'warn', 'error'],
|
||||||
@@ -54,7 +51,7 @@ export const downloadHtmlInBackground = (events: unknown[]) => {
|
|||||||
</body>
|
</body>
|
||||||
</html>`;
|
</html>`;
|
||||||
|
|
||||||
// 下载逻辑 (保持不变)
|
// 下载逻辑
|
||||||
const blob = new Blob([htmlContent], { type: 'text/html' });
|
const blob = new Blob([htmlContent], { type: 'text/html' });
|
||||||
const reader = new FileReader();
|
const reader = new FileReader();
|
||||||
reader.onload = () => {
|
reader.onload = () => {
|
||||||
|
|||||||
Reference in New Issue
Block a user