chrome.runtime.onInstalled.addListener(() => { console.log("Background script: Extension installed or updated."); chrome.contextMenus.create({ id: "convertText", title: "Convertir en écriture inclusive", contexts: ["selection"] }); console.log("Background script: Context menu item created."); }); chrome.contextMenus.onClicked.addListener((info, tab) => { console.log("Background script: Context menu item clicked.", info); if (info.menuItemId === "convertText" && info.selectionText && tab && tab.id) { console.log(`Background script: Selected text: "${info.selectionText}" in tab ID: ${tab.id}`); // First, ensure the content script is injected into the tab. // This is crucial if the tab was opened before the extension was installed/updated, // or if the content script somehow failed to load. chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] }, () => { // Check for runtime.lastError to see if injection failed if (chrome.runtime.lastError) { console.error("Background script: Error injecting content script:", chrome.runtime.lastError.message); return; } console.log("Background script: Content script injected/confirmed."); // After the content script is (re)injected, send the message. chrome.tabs.sendMessage(tab.id, { action: "convertSelectedText", text: info.selectionText }).then(response => { console.log("Background script: Message sent to content script. Response:", response); }).catch(error => { // Catch potential errors if the receiving end still doesn't exist // (e.g., tab closed immediately after context menu click). console.error("Background script: Error sending message to content script:", error); }); }); } else { console.log("Background script: Context menu click conditions not met."); } });