Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 36 additions & 12 deletions background.js
Original file line number Diff line number Diff line change
Expand Up @@ -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://)
Expand All @@ -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 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We may ultimately want to do some error handling around the sendMessage call above and loading the content script below, but that can be another PR.

// 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' });
}
};

Expand Down