feat:
1、移动popup的page、components 2、更新wxt的host权限 3、验证message传递逻辑
This commit is contained in:
+31
-31
@@ -2,8 +2,7 @@ import '../.wxt/types/imports.d.ts';
|
||||
import { browser } from 'wxt/browser';
|
||||
|
||||
export default defineBackground(() => {
|
||||
console.log('Hello background!', { id: browser.runtime.id });
|
||||
|
||||
// 监听扩展安装或更新事件
|
||||
browser.runtime.onInstalled.addListener(async ({ reason }) => {
|
||||
if (reason === 'install') {
|
||||
// 第一次安装扩展时触发
|
||||
@@ -28,41 +27,42 @@ export default defineBackground(() => {
|
||||
}
|
||||
});
|
||||
|
||||
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 });
|
||||
// 监听来自 popup script 的消息
|
||||
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
|
||||
if (msg.type === messages.popup.checkStatus) {
|
||||
console.log('[bg] checkStatus received');
|
||||
// void chrome.runtime.sendMessage({ type: messages.content.checkStatus });
|
||||
sendToActiveTab({ type: messages.content.checkStatus })
|
||||
.then(() => {
|
||||
sendResponse({ ok: true });
|
||||
})
|
||||
.catch(() => {
|
||||
sendResponse({ ok: false });
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
if (msg.type === 'DOWNLOAD') {
|
||||
console.log('[bg] DOWNLOAD received');
|
||||
if (msg.type === messages.offscreen.to.startRecording) {
|
||||
console.log('[bg] startRecording received');
|
||||
sendResponse({ ok: true });
|
||||
// void browser.runtime.sendMessage({ type: messages.popup.to.started });
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
// async function _sendToActiveTab(message: {
|
||||
// type: string;
|
||||
// data?: unknown;
|
||||
// activeTabId?: number;
|
||||
// [key: string]: unknown;
|
||||
// }) {
|
||||
// const activeTabs = await browser.tabs.query({
|
||||
// active: true,
|
||||
// currentWindow: true,
|
||||
// });
|
||||
// const activeTab = activeTabs[0];
|
||||
// const sendTo = message.activeTabId || activeTab.id;
|
||||
// await browser.tabs.sendMessage(sendTo!, message);
|
||||
// }
|
||||
async function sendToActiveTab(message: {
|
||||
type: string;
|
||||
data?: unknown;
|
||||
activeTabId?: number;
|
||||
[key: string]: unknown;
|
||||
}) {
|
||||
const activeTabs = await chrome.tabs.query({
|
||||
active: true,
|
||||
currentWindow: true,
|
||||
});
|
||||
const activeTab = activeTabs[0];
|
||||
const sendTo = message.activeTabId || activeTab.id;
|
||||
await chrome.tabs.sendMessage(sendTo!, message);
|
||||
}
|
||||
});
|
||||
|
||||
+6
-14
@@ -1,25 +1,17 @@
|
||||
import '../.wxt/types/imports.d.ts';
|
||||
import { browser } from 'wxt/browser';
|
||||
|
||||
export default defineContentScript({
|
||||
// matches: ['*://*.google.com/*'],
|
||||
matches: ['<all_urls>'],
|
||||
runAt: 'document_start',
|
||||
main() {
|
||||
console.log('Content script loaded successfully', { id: browser.runtime.id });
|
||||
|
||||
chrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {
|
||||
if (message.type === 'START_RECORD') {
|
||||
// startRecord();
|
||||
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' });
|
||||
// 监听来自 background script 的消息
|
||||
chrome.runtime.onMessage.addListener((msg: { type: string }, _sender, sendResponse) => {
|
||||
if (msg.type === messages.content.checkStatus) {
|
||||
console.log('[content] checkStatus received');
|
||||
sendResponse({ ok: true });
|
||||
} else {
|
||||
console.log('Unknown command received in content script');
|
||||
sendResponse({ status: 'Unknown command' });
|
||||
console.log('[content] unknown message type:', msg.type);
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { HashRouter as Router, Routes, Route, NavLink } from 'react-router-dom';
|
||||
import { useState, useEffect } from 'react';
|
||||
import TimestampPage from '../../pages/TimestampPage';
|
||||
import RecordeReplayPage from '../../pages/RecordeReplayPage';
|
||||
import TimestampPage from './pages/TimestampPage';
|
||||
import RecordeReplayPage from './pages/RecordeReplayPage';
|
||||
import './App.css';
|
||||
|
||||
const navItems = [
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { formatWithDate, formatWithZone } from '../utils/timeUtils';
|
||||
import { formatWithDate, formatWithZone } from '../../../utils/timeUtils';
|
||||
import { useState, useCallback } from 'react';
|
||||
|
||||
/**
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
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 { AppState } from '../types';
|
||||
import { messages } from '../../../utils/messages';
|
||||
|
||||
const RecordeReplayPage = () => {
|
||||
const [status, setStatus] = useState<AppState>(AppState.READ);
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
|
||||
const getActiveTab = async () => {
|
||||
@@ -8,14 +11,29 @@ const RecordeReplayPage = () => {
|
||||
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(() => {
|
||||
const checkStatus = async () => {
|
||||
const tab = await getActiveTab();
|
||||
if (tab?.id) {
|
||||
try {
|
||||
// 发送一个检查状态的命令(需要在 content script 增加对应的处理)
|
||||
// 或者使用 storage 方案(推荐)
|
||||
// 这里假设你用 sendMessage 检查
|
||||
chrome.tabs.sendMessage(tab.id, { command: 'CHECK_STATUS' }, (response) => {
|
||||
// 如果 content script 没加载,这里会报错,需要 catch
|
||||
if (chrome.runtime.lastError) {
|
||||
@@ -24,6 +42,8 @@ const RecordeReplayPage = () => {
|
||||
}
|
||||
if (response?.isRecording) {
|
||||
setIsRecording(true);
|
||||
setStatus(AppState.RECORDING);
|
||||
console.log(status);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
@@ -32,37 +52,11 @@ const RecordeReplayPage = () => {
|
||||
}
|
||||
};
|
||||
checkStatus();
|
||||
}, []);
|
||||
}, [status]);
|
||||
|
||||
const toggleRecording = async () => {
|
||||
const tab = await getActiveTab();
|
||||
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 (
|
||||
@@ -71,9 +65,6 @@ const RecordeReplayPage = () => {
|
||||
<button className={`action-btn ${isRecording ? 'stop-btn' : ''}`} onClick={toggleRecording}>
|
||||
{isRecording ? '停止录制' : '开始录制'}
|
||||
</button>
|
||||
<button className="action-btn" onClick={test}>
|
||||
test
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -0,0 +1,4 @@
|
||||
export enum AppState {
|
||||
READ = 'ready',
|
||||
RECORDING = 'recording',
|
||||
}
|
||||
+13
-3
@@ -1,12 +1,22 @@
|
||||
export const messages = {
|
||||
content: {
|
||||
popup: {
|
||||
from: {
|
||||
|
||||
start: 'popup:start',
|
||||
},
|
||||
to: {
|
||||
stoped: 'popup:stoped',
|
||||
started: 'popup:started',
|
||||
},
|
||||
checkStatus: 'popup:check-status',
|
||||
ready: 'popup:ready',
|
||||
},
|
||||
content: {
|
||||
from: {},
|
||||
to: {
|
||||
startRecording: 'content:start-recording',
|
||||
stopRecording: 'content:stop-recording',
|
||||
}
|
||||
},
|
||||
checkStatus: 'content:check-status',
|
||||
},
|
||||
offscreen: {
|
||||
to: {
|
||||
|
||||
@@ -16,6 +16,7 @@ export default defineConfig({
|
||||
'tabs',
|
||||
'offscreen',
|
||||
],
|
||||
host_permissions: ['<all_urls>'],
|
||||
action: {
|
||||
default_title: 'Testing Tools',
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user