Update
This commit is contained in:
+21
-37
@@ -1,6 +1,6 @@
|
||||
console.log('[XAI Background] ✅ Service worker started');
|
||||
|
||||
// ===== TẠO MENU =====
|
||||
// ===== MENU =====
|
||||
chrome.runtime.onInstalled.addListener(() => {
|
||||
chrome.contextMenus.create({
|
||||
id: 'writeComment',
|
||||
@@ -10,69 +10,53 @@ chrome.runtime.onInstalled.addListener(() => {
|
||||
});
|
||||
});
|
||||
|
||||
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
|
||||
// FIRE & FORGET — không đợi content trả lời
|
||||
chrome.contextMenus.onClicked.addListener((info, tab) => {
|
||||
if (info.menuItemId !== 'writeComment' || !tab?.id) return;
|
||||
try {
|
||||
await chrome.tabs.sendMessage(tab.id, { action: 'OPEN_FORM' });
|
||||
} catch (err) {
|
||||
console.error('[XAI Background] ❌ Không gọi được content script:', err.message);
|
||||
}
|
||||
chrome.tabs.sendMessage(tab.id, { action: 'OPEN_FORM' }).catch(() => {});
|
||||
});
|
||||
|
||||
// ===== NHẬN YÊU CẦU TỪ CONTENT =====
|
||||
// LUÔN GỌI sendResponse(), KHÔNG BAO GIỜ return true
|
||||
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
||||
if (request.action === 'GENERATE_COMMENT') {
|
||||
// Gọi API async riêng, không await ở đây
|
||||
handleGenerate(request.data, sender.tab.id);
|
||||
|
||||
// Đóng kênh ngay để tránh lỗi "channel closed"
|
||||
sendResponse({ received: true });
|
||||
return false;
|
||||
}
|
||||
sendResponse({ unknown: true });
|
||||
return false;
|
||||
});
|
||||
|
||||
// ===== GỌI API: ĐỌC CONFIG TỪ STORAGE =====
|
||||
async function handleGenerate({ text, lang, tone, angle }, tabId) {
|
||||
console.log('[XAI Background] ⏳ Đọc config từ storage...');
|
||||
|
||||
const config = await chrome.storage.local.get(['apiUrl', 'apiKey']);
|
||||
|
||||
if (!config.apiUrl || !config.apiKey) {
|
||||
console.error('[XAI Background] ❌ Thiếu API config');
|
||||
const cfg = await chrome.storage.local.get(['apiUrl', 'apiKey']);
|
||||
if (!cfg.apiUrl || !cfg.apiKey) {
|
||||
await chrome.tabs.sendMessage(tabId, {
|
||||
action: 'SHOW_ERROR',
|
||||
error: '⚠️ Chưa cấu hình API.\n\n👉 Bấm tab ⚙️ Config để nhập URL và Key.'
|
||||
});
|
||||
}).catch(() => {});
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
originalPost: text,
|
||||
language: lang,
|
||||
tone: tone?tone.toLowerCase():undefined,
|
||||
angle: angle?angle.toLowerCase():undefined,
|
||||
};
|
||||
console.log('[XAI Background] 📤 Payload:', JSON.stringify(payload, null, 2));
|
||||
console.log('[XAI Background] 🌐 URL:', config.apiUrl);
|
||||
|
||||
try {
|
||||
const res = await fetch(config.apiUrl, {
|
||||
const payload = {
|
||||
originalPost: text,
|
||||
language: lang,
|
||||
tone: tone?tone.toLowerCase():undefined,
|
||||
angle: angle?angle.toLowerCase():undefined,
|
||||
};
|
||||
const res = await fetch(cfg.apiUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${config.apiKey}`
|
||||
'Authorization': `Bearer ${cfg.apiKey}`
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
console.log('[XAI Background] 📥 Response:', res.status, data);
|
||||
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
|
||||
const comment = data.comment || data.text || JSON.stringify(data);
|
||||
await chrome.tabs.sendMessage(tabId, { action: 'SHOW_RESULT', comment });
|
||||
await chrome.tabs.sendMessage(tabId, { action: 'SHOW_RESULT', comment }).catch(() => {});
|
||||
} catch (err) {
|
||||
console.error('[XAI Background] ❌ Lỗi fetch:', err.message);
|
||||
await chrome.tabs.sendMessage(tabId, { action: 'SHOW_ERROR', error: err.message });
|
||||
await chrome.tabs.sendMessage(tabId, { action: 'SHOW_ERROR', error: err.message }).catch(() => {});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user