Files
x-poster-client/chrom-ext/background.js
T
2026-05-15 10:02:53 +00:00

63 lines
2.1 KiB
JavaScript

// ===== 1. TẠO CONTEXT MENU =====
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: 'writeComment',
title: '✍️ Viết comment',
contexts: ['all'],
documentUrlPatterns: ['https://x.com/*', 'https://twitter.com/*']
});
});
// ===== 2. KHI CLICK VÀO MENU =====
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'writeComment') {
chrome.tabs.sendMessage(tab.id, { action: 'OPEN_FORM' }).catch(() => {
// Nếu content script chưa sẵn sàng (hiếm) thì bỏ qua
});
}
});
// ===== 3. NHẬN YÊU CẦU TỪ CONTENT SCRIPT VÀ GỌI API =====
chrome.runtime.onMessage.addListener((request, sender) => {
if (request.action === 'GENERATE_COMMENT') {
callYourAPI(request.data, sender.tab.id);
}
});
async function callYourAPI({
text,
tone,
angle,
language
}, tabId) {
try {
// ⚠️ THAY BẰNG ENDPOINT CỦA BẠN
const API_URL = 'https://gamerdota0042-himalayas.nord:3000';
const commentApi='/content-writer/comment'
const API_KEY = 'YOUR_API_KEY_HERE'; // Nên chuyển sang chrome.storage nếu publish
const res = await fetch(`${API_URL}${commentApi}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
originalPost: text,
tone: tone,
angle: angle,
language,
})
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
// Giả định API trả về: { comment: "..." }
const comment = data.comment || data.text || JSON.stringify(data);
chrome.tabs.sendMessage(tabId, { action: 'SHOW_RESULT', comment });
} catch (err) {
chrome.tabs.sendMessage(tabId, { action: 'SHOW_ERROR', error: err.message });
}
}