fix:修复复制按钮

This commit is contained in:
雨霖铃
2026-01-12 22:14:01 +08:00
parent 7079334562
commit db46210096
3 changed files with 55 additions and 7 deletions
+21 -4
View File
@@ -1,8 +1,25 @@
console.log('Background script loaded');
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === 'start') { console.log('收到消息:', request);
if (request.action === 'copy') {
console.log('开始复制文本:', request.text);
navigator.clipboard.writeText(request.text) navigator.clipboard.writeText(request.text)
.then(() => sendResponse({success: true})) .then(() => {
.catch((err) => console.log(err)); console.log('复制成功');
return true; sendResponse({success: true});
})
.catch((err) => {
console.error('复制失败:', err);
sendResponse({success: false, error: err.message});
});
return true; // 保持消息端口开放以支持异步响应
} }
// 对于未知的操作,也返回响应
sendResponse({success: false, error: '未知操作'});
return false;
}); });
+2 -1
View File
@@ -4,7 +4,8 @@
"version": "1.0", "version": "1.0",
"description": "A Chrome Extension with React Router: User List + Actions Pages", "description": "A Chrome Extension with React Router: User List + Actions Pages",
"permissions": [ "permissions": [
"storage" "storage",
"clipboardWrite"
], ],
"background": { "background": {
"service_worker": "background.js" "service_worker": "background.js"
+32 -2
View File
@@ -36,22 +36,52 @@ const CopyButton = ({
const handleCopy = async () => { const handleCopy = async () => {
try { try {
console.log('开始复制:', text);
// 首先尝试直接使用navigator.clipboard(在popup页面中可能可用)
try {
console.log('尝试直接使用navigator.clipboard复制');
await navigator.clipboard.writeText(text.toString());
console.log('直接复制成功');
handleCopySuccess();
return;
} catch (directError) {
console.log('直接复制失败,尝试使用Chrome扩展API:', directError);
}
// 如果直接复制失败,尝试使用Chrome扩展API
if (chrome && chrome.runtime && chrome.runtime.sendMessage) { if (chrome && chrome.runtime && chrome.runtime.sendMessage) {
console.log('使用Chrome扩展API复制');
// 使用Chrome扩展API复制
chrome.runtime.sendMessage({ chrome.runtime.sendMessage({
action: 'copy', action: 'copy',
text: text text: text
}, (response) => { }, (response) => {
console.log('收到background响应:', response, 'lastError:', chrome.runtime.lastError);
// 检查是否有运行时错误
if (chrome.runtime.lastError) {
console.error('Chrome运行时错误:', chrome.runtime.lastError.message);
handleCopyError();
return;
}
// 检查响应
if (response && response.success) { if (response && response.success) {
console.log('通过background复制成功');
handleCopySuccess(); handleCopySuccess();
} else { } else {
console.error('通过background复制失败:', response?.error);
handleCopyError(); handleCopyError();
} }
}); });
} else { } else {
await navigator.clipboard.writeText(text.toString()); console.error('没有可用的复制方法');
handleCopySuccess(); handleCopyError();
} }
} catch (err) { } catch (err) {
console.error('复制过程中发生错误:', err);
handleCopyError(); handleCopyError();
} }
}; };