It is not clear to me if a content script automatically gets loaded in the sidebar when the panel is set to an external url.
It also seems that the sidebar isn’t assigned a tabId (which awfully complicates things!) as running the following code in my background script produces an error stating that tab is undefined. Without the tabId, I’m unable to execute script dynamically or send a message from the background script to the content script in the sidebar.
if (!multisearch && contextsearch_openSearchResultsInSidebar) {
let tabUrl = url + '#_sidebar';
// If single search and open in sidebar
browser.sidebarAction.setPanel({ panel: tabUrl });
browser.sidebarAction.setTitle({ title: 'Search results' });
if (id.startsWith('chatgpt-')) {
if (logToConsole) console.log(id);
// Once the content script is ready, trigger the ask function
const promptText = getPromptText(id, prompt);
const tabs = await browser.tabs.query({ url: tabUrl });
const tab = tabs[0];
const tabId = tab.id;
if (logToConsole) console.log(tabId, tab);
try {
// Wait for the content script to signal that it is fully loaded
await browser.tabs.executeScript(tabId, {
code: 'typeof browser.runtime !== "undefined";'
});
if (logToConsole) console.log('Content script loaded, sending message.');
await sendMessageToTab(tab, {
action: "askPrompt",
data: { url: tabUrl, prompt: promptText }
});
} catch (error) {
if (logToConsole) console.log('Error: Content script not loaded or could not execute script:', error);
}
}
}
The problem I’m trying to solve is: I’d like to open an external website like chatgpt.com in the sidebar. Once the web page is loaded, I’d like to insert some prompt text in the right textarea and then submit the prompt. This is where the content script comes into play. How can I handle this situation?