diff --git a/background.js b/background.js index 692b51b..1ec1d08 100644 --- a/background.js +++ b/background.js @@ -4,6 +4,33 @@ // Detect browser API const browserAPI = typeof browser !== 'undefined' ? browser : chrome; +// Check if content script is loaded by trying to send a message +const isContentScriptLoaded = async (tabId) => { + try { + await browserAPI.tabs.sendMessage(tabId, { action: 'ping' }); + return true; + } catch { + return false; + } +}; + +// Send a message with retries (for after injection) +const sendMessageWithRetry = async (tabId, message, maxRetries = 10) => { + for (let i = 0; i < maxRetries; i++) { + try { + await new Promise(resolve => setTimeout(resolve, 100 * (i + 1))); // 100ms, 200ms, 300ms... + await browserAPI.tabs.sendMessage(tabId, message); + return; // Success! + } catch (error) { + if (i === maxRetries - 1) { + console.error('Failed to communicate with content script:', error.message); + throw error; + } + // Continue to next retry + } + } +}; + // Handle extension icon click const handleIconClick = async (tab) => { // Check if we're on a valid page (not chrome://, about:, file://) @@ -16,24 +43,21 @@ const handleIconClick = async (tab) => { return; } - try { - // Try to send a message first to see if content script is already loaded + // Check if content script is already loaded + const isLoaded = await isContentScriptLoaded(tab.id); + + if (isLoaded) { + // Content script already there, send message await browserAPI.tabs.sendMessage(tab.id, { action: 'togglePanel' }); - - } catch (error) { - // If message fails, content.js isn't loaded. Inject it, and execute the content script + } else { + // Content script not loaded yet - inject it first await browserAPI.scripting.executeScript({ target: { tabId: tab.id }, files: ['content.js'] }); - - // Wait a moment for the script to initialize - await new Promise(resolve => setTimeout(resolve, 150)); - - // Send a message after injection - await browserAPI.tabs.sendMessage(tab.id, { action: 'togglePanel' }); - console.error(`Error in handleIconClick: ${error.message}`); + // Wait for content script to initialize, then send message + await sendMessageWithRetry(tab.id, { action: 'togglePanel' }); } };