-
So I am trying to automate input to a page. After submitting this input, I am getting redirected a bunch of times but I get to the original page eventually. My goal is to start this process from the UI like so: 1) MyUi.svelte async function startUploader() {
await browser.runtime.sendMessage({ command: 'start' });
} 2) background.ts let automationRunning = false;
browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
if (message.command === 'start') {
automationRunning = true;
//(this was recommended by chatgpt, I don't quite understand the difference between sendResponse() and return)
sendResponse({ status: 'autoRunAmazonUploader set to true' });
// Get the active tab
const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
if (tab?.id) {
// Send a message to the content script to start the async operation
console.log('sending message to tab', tab.id);
browser.tabs.sendMessage(tab.id, { greeting: 'hello' });
}
}
// Return true to indicate you will send a response asynchronously (this was recommended by chatgpt, I don't quite understand the difference between sendResponse() and return)
return true;
}); 3) content-script.ts export default defineContentScript({
async main(ctx) {
browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
await myAutomationCodeThatResultsInARedirect();
});
},
}); 4) background.ts browser.webNavigation.onHistoryStateUpdated.addListener(async (details) => {
if(!automationRunning) return ;
const response = await browser.tabs.sendMessage(details.tabId, { greeting: 'hello' });
}); for some reason the 4th step throws an error |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
I don't know if it's the main cause, but one problem is in your use of To respond to a message asynchronously, you should either:
You cannot do both. These three snippets behave the same:
I always use the third option. IMO, it's the simplest and easiest to read. Now let's look at yours: browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
if (message.command === 'start') {
sendResponse({ ... });
}
return true;
}); You're using an |
Beta Was this translation helpful? Give feedback.
I don't know if it's the main cause, but one problem is in your use of
sendResponse
.To respond to a message asynchronously, you should either:
You cannot do both. These three snippets behave the same:
Synchronously return true and use
sendResponse
Don't use an async function, but return a promise