fix:修复复制按钮
This commit is contained in:
+22
-5
@@ -1,8 +1,25 @@
|
||||
console.log('Background script loaded');
|
||||
|
||||
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)
|
||||
.then(() => sendResponse({success: true}))
|
||||
.catch((err) => console.log(err));
|
||||
return true;
|
||||
}
|
||||
.then(() => {
|
||||
console.log('复制成功');
|
||||
sendResponse({success: true});
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('复制失败:', err);
|
||||
sendResponse({success: false, error: err.message});
|
||||
});
|
||||
|
||||
return true; // 保持消息端口开放以支持异步响应
|
||||
}
|
||||
|
||||
// 对于未知的操作,也返回响应
|
||||
sendResponse({success: false, error: '未知操作'});
|
||||
return false;
|
||||
});
|
||||
@@ -4,7 +4,8 @@
|
||||
"version": "1.0",
|
||||
"description": "A Chrome Extension with React Router: User List + Actions Pages",
|
||||
"permissions": [
|
||||
"storage"
|
||||
"storage",
|
||||
"clipboardWrite"
|
||||
],
|
||||
"background": {
|
||||
"service_worker": "background.js"
|
||||
|
||||
@@ -36,22 +36,52 @@ const CopyButton = ({
|
||||
|
||||
const handleCopy = async () => {
|
||||
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) {
|
||||
console.log('使用Chrome扩展API复制');
|
||||
|
||||
// 使用Chrome扩展API复制
|
||||
chrome.runtime.sendMessage({
|
||||
action: 'copy',
|
||||
text: text
|
||||
}, (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) {
|
||||
console.log('通过background复制成功');
|
||||
handleCopySuccess();
|
||||
} else {
|
||||
console.error('通过background复制失败:', response?.error);
|
||||
handleCopyError();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
await navigator.clipboard.writeText(text.toString());
|
||||
handleCopySuccess();
|
||||
console.error('没有可用的复制方法');
|
||||
handleCopyError();
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('复制过程中发生错误:', err);
|
||||
handleCopyError();
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user