1、移动popup的page、components
2、更新wxt的host权限
3、验证message传递逻辑
This commit is contained in:
雨霖铃
2026-02-01 00:21:36 +08:00
parent 4213e70697
commit 0b70c0c0c1
12 changed files with 83 additions and 85 deletions
+30 -30
View File
@@ -2,8 +2,7 @@ import '../.wxt/types/imports.d.ts';
import { browser } from 'wxt/browser'; import { browser } from 'wxt/browser';
export default defineBackground(() => { export default defineBackground(() => {
console.log('Hello background!', { id: browser.runtime.id }); // 监听扩展安装或更新事件
browser.runtime.onInstalled.addListener(async ({ reason }) => { browser.runtime.onInstalled.addListener(async ({ reason }) => {
if (reason === 'install') { if (reason === 'install') {
// 第一次安装扩展时触发 // 第一次安装扩展时触发
@@ -28,41 +27,42 @@ export default defineBackground(() => {
} }
}); });
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { // 监听来自 popup script 的消息
// 处理来自其他部分的消息 chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
console.log('[bg] message received:', msg, sender.tab); if (msg.type === messages.popup.checkStatus) {
console.log('[bg] checkStatus received');
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { // void chrome.runtime.sendMessage({ type: messages.content.checkStatus });
const currentTab = tabs[0]; sendToActiveTab({ type: messages.content.checkStatus })
console.log('[bg] 真正活跃的页面标题是:', currentTab?.title); .then(() => {
sendResponse({ ok: true, title: currentTab?.title });
});
if (msg.type === 'CREATE_OFFSCREEN') {
console.log('[bg] offscreen created');
sendResponse({ ok: true }); sendResponse({ ok: true });
})
.catch(() => {
sendResponse({ ok: false });
});
return true;
} }
if (msg.type === 'DOWNLOAD') { if (msg.type === messages.offscreen.to.startRecording) {
console.log('[bg] DOWNLOAD received'); console.log('[bg] startRecording received');
sendResponse({ ok: true }); sendResponse({ ok: true });
// void browser.runtime.sendMessage({ type: messages.popup.to.started });
} }
return true; return true;
}); });
// async function _sendToActiveTab(message: { async function sendToActiveTab(message: {
// type: string; type: string;
// data?: unknown; data?: unknown;
// activeTabId?: number; activeTabId?: number;
// [key: string]: unknown; [key: string]: unknown;
// }) { }) {
// const activeTabs = await browser.tabs.query({ const activeTabs = await chrome.tabs.query({
// active: true, active: true,
// currentWindow: true, currentWindow: true,
// }); });
// const activeTab = activeTabs[0]; const activeTab = activeTabs[0];
// const sendTo = message.activeTabId || activeTab.id; const sendTo = message.activeTabId || activeTab.id;
// await browser.tabs.sendMessage(sendTo!, message); await chrome.tabs.sendMessage(sendTo!, message);
// } }
}); });
+6 -14
View File
@@ -1,25 +1,17 @@
import '../.wxt/types/imports.d.ts'; import '../.wxt/types/imports.d.ts';
import { browser } from 'wxt/browser';
export default defineContentScript({ export default defineContentScript({
// matches: ['*://*.google.com/*'], // matches: ['*://*.google.com/*'],
matches: ['<all_urls>'], matches: ['<all_urls>'],
runAt: 'document_start', runAt: 'document_start',
main() { main() {
console.log('Content script loaded successfully', { id: browser.runtime.id }); // 监听来自 background script 的消息
chrome.runtime.onMessage.addListener((msg: { type: string }, _sender, sendResponse) => {
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => { if (msg.type === messages.content.checkStatus) {
if (message.type === 'START_RECORD') { console.log('[content] checkStatus received');
// startRecord(); sendResponse({ ok: true });
console.log('Start recording command received in content script');
sendResponse({ status: 'Recording started' });
} else if (message.type === 'STOP_RECORD') {
// stopRecord();
console.log('Stop recording command received in content script');
sendResponse({ status: 'Recording stopped' });
} else { } else {
console.log('Unknown command received in content script'); console.log('[content] unknown message type:', msg.type);
sendResponse({ status: 'Unknown command' });
} }
return true; return true;
+2 -2
View File
@@ -1,7 +1,7 @@
import { HashRouter as Router, Routes, Route, NavLink } from 'react-router-dom'; import { HashRouter as Router, Routes, Route, NavLink } from 'react-router-dom';
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import TimestampPage from '../../pages/TimestampPage'; import TimestampPage from './pages/TimestampPage';
import RecordeReplayPage from '../../pages/RecordeReplayPage'; import RecordeReplayPage from './pages/RecordeReplayPage';
import './App.css'; import './App.css';
const navItems = [ const navItems = [
@@ -1,4 +1,4 @@
import { formatWithDate, formatWithZone } from '../utils/timeUtils'; import { formatWithDate, formatWithZone } from '../../../utils/timeUtils';
import { useState, useCallback } from 'react'; import { useState, useCallback } from 'react';
/** /**
@@ -1,5 +1,5 @@
import { useState, useCallback } from 'react'; import { useState, useCallback } from 'react';
import { formatWithZone } from '../utils/timeUtils'; import { formatWithZone } from '../../../utils/timeUtils';
/** /**
* *
@@ -1,6 +1,9 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { AppState } from '../types';
import { messages } from '../../../utils/messages';
const RecordeReplayPage = () => { const RecordeReplayPage = () => {
const [status, setStatus] = useState<AppState>(AppState.READ);
const [isRecording, setIsRecording] = useState(false); const [isRecording, setIsRecording] = useState(false);
const getActiveTab = async () => { const getActiveTab = async () => {
@@ -8,14 +11,29 @@ const RecordeReplayPage = () => {
return tab; return tab;
}; };
useEffect(() => {
const handleMessage = (msg: { type: string }) => {
if (msg.type === messages.popup.ready) {
setStatus(AppState.READ);
} else if (msg.type === messages.popup.to.started) {
setStatus(AppState.RECORDING);
} else if (msg.type === messages.popup.to.stoped) {
setStatus(AppState.READ);
}
};
browser.runtime.onMessage.addListener(handleMessage);
browser.runtime.sendMessage({ type: messages.popup.checkStatus });
return () => browser.runtime.onMessage.removeListener(handleMessage);
}, []);
useEffect(() => { useEffect(() => {
const checkStatus = async () => { const checkStatus = async () => {
const tab = await getActiveTab(); const tab = await getActiveTab();
if (tab?.id) { if (tab?.id) {
try { try {
// 发送一个检查状态的命令(需要在 content script 增加对应的处理)
// 或者使用 storage 方案(推荐)
// 这里假设你用 sendMessage 检查
chrome.tabs.sendMessage(tab.id, { command: 'CHECK_STATUS' }, (response) => { chrome.tabs.sendMessage(tab.id, { command: 'CHECK_STATUS' }, (response) => {
// 如果 content script 没加载,这里会报错,需要 catch // 如果 content script 没加载,这里会报错,需要 catch
if (chrome.runtime.lastError) { if (chrome.runtime.lastError) {
@@ -24,6 +42,8 @@ const RecordeReplayPage = () => {
} }
if (response?.isRecording) { if (response?.isRecording) {
setIsRecording(true); setIsRecording(true);
setStatus(AppState.RECORDING);
console.log(status);
} }
}); });
} catch (e) { } catch (e) {
@@ -32,37 +52,11 @@ const RecordeReplayPage = () => {
} }
}; };
checkStatus(); checkStatus();
}, []); }, [status]);
const toggleRecording = async () => { const toggleRecording = async () => {
const tab = await getActiveTab(); const tab = await getActiveTab();
if (!tab?.id) return; if (!tab?.id) return;
// 2. 无论开始还是停止,都重新获取当前的 Tab ID
// 不要依赖 state 中的 tabId,因为 popup 关闭后 state 会丢
const nextState = !isRecording;
const command = nextState ? 'START_RECORD' : 'STOP_RECORD';
chrome.tabs.sendMessage(tab.id, { type: command }, (response) => {
// 处理 runtime.lastError 防止报错红字
if (chrome.runtime.lastError) {
console.error('通信失败:', chrome.runtime.lastError.message);
alert('请刷新当前网页后再试(Content Script 未注入)');
return;
}
console.log('Content回复:', response);
if (response?.status) {
// 只有收到确认回复后,才改变 UI 状态
setIsRecording(nextState);
}
});
};
const test = async () => {
await chrome.runtime.sendMessage({ type: 'test' }).then((response) => {
console.log('[popup] Response from background:', response);
});
}; };
return ( return (
@@ -71,9 +65,6 @@ const RecordeReplayPage = () => {
<button className={`action-btn ${isRecording ? 'stop-btn' : ''}`} onClick={toggleRecording}> <button className={`action-btn ${isRecording ? 'stop-btn' : ''}`} onClick={toggleRecording}>
{isRecording ? '停止录制' : '开始录制'} {isRecording ? '停止录制' : '开始录制'}
</button> </button>
<button className="action-btn" onClick={test}>
test
</button>
</div> </div>
</div> </div>
); );
+4
View File
@@ -0,0 +1,4 @@
export enum AppState {
READ = 'ready',
RECORDING = 'recording',
}
+13 -3
View File
@@ -1,12 +1,22 @@
export const messages = { export const messages = {
content: { popup: {
from: { from: {
start: 'popup:start',
}, },
to: {
stoped: 'popup:stoped',
started: 'popup:started',
},
checkStatus: 'popup:check-status',
ready: 'popup:ready',
},
content: {
from: {},
to: { to: {
startRecording: 'content:start-recording', startRecording: 'content:start-recording',
stopRecording: 'content:stop-recording', stopRecording: 'content:stop-recording',
} },
checkStatus: 'content:check-status',
}, },
offscreen: { offscreen: {
to: { to: {
+1
View File
@@ -16,6 +16,7 @@ export default defineConfig({
'tabs', 'tabs',
'offscreen', 'offscreen',
], ],
host_permissions: ['<all_urls>'],
action: { action: {
default_title: 'Testing Tools', default_title: 'Testing Tools',
}, },