62 lines
2.2 KiB
JavaScript
62 lines
2.2 KiB
JavaScript
console.log('[XAI Background] ✅ Service worker started');
|
|
|
|
// ===== MENU =====
|
|
chrome.runtime.onInstalled.addListener(() => {
|
|
chrome.contextMenus.create({
|
|
id: 'writeComment',
|
|
title: '✍️ Viết comment',
|
|
contexts: ['all'],
|
|
documentUrlPatterns: ['https://x.com/*']
|
|
});
|
|
});
|
|
|
|
// FIRE & FORGET — không đợi content trả lời
|
|
chrome.contextMenus.onClicked.addListener((info, tab) => {
|
|
if (info.menuItemId !== 'writeComment' || !tab?.id) return;
|
|
chrome.tabs.sendMessage(tab.id, { action: 'OPEN_FORM' }).catch(() => {});
|
|
});
|
|
|
|
// LUÔN GỌI sendResponse(), KHÔNG BAO GIỜ return true
|
|
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
if (request.action === 'GENERATE_COMMENT') {
|
|
handleGenerate(request.data, sender.tab.id);
|
|
sendResponse({ received: true });
|
|
return false;
|
|
}
|
|
sendResponse({ unknown: true });
|
|
return false;
|
|
});
|
|
|
|
async function handleGenerate({ text, lang, tone, angle }, tabId) {
|
|
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;
|
|
}
|
|
|
|
try {
|
|
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 ${cfg.apiKey}`
|
|
},
|
|
body: JSON.stringify(payload)
|
|
});
|
|
const data = await res.json();
|
|
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 }).catch(() => {});
|
|
} catch (err) {
|
|
await chrome.tabs.sendMessage(tabId, { action: 'SHOW_ERROR', error: err.message }).catch(() => {});
|
|
}
|
|
} |