-
-
Notifications
You must be signed in to change notification settings - Fork 277
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
The behavior of browser.runtime.onMessage #1560
Comments
This is not how messaging works. I'll clear up a couple of misconnecptions here:
To return a response, you have two options:
Keep in mind that as soon as you make the callback Let's cleanup your code. Personally, I prefer to use promises in my message handlers, but I'll show how to do both. async function someAsyncWork(): Promise<string> {
return message + "2";
};
browser.runtime.onMessage.addListener((message) => {
return someAsyncWork();
});
Or using function someAsyncWorkWithCallback(cb: () => void): void {
setTimeout(cb, 1000);
}
browser.runtime.onMessage.addListener((message, _, sendResponse) => {
someAsyncWorkWithCallback(() => {
sendResponse(message + "2")
});
return true
}); Or in your case, if we return a value immediately, you still need to either: return a promise, or return browser.runtime.onMessage.addListener((message) => {
return Promise.resolve(message + "2");
}); This is the correct way to write message handlers. It works on all active browser and manifest combinations (Firefox MV2, Firefox MV3, Chrome MV3, Safari MV2, Safari MV3). It does not work on Chrome MV2 (doesn't support promises, only |
Thank you for your reply!
Based on the above, I successfully return a response using the following method: // entrypoints/content.ts
async function someAsyncWork(message: string, sendResponse: (response?: any) => void) {
sendResponse(message + "2");
}
export default defineContentScript({
matches: ["<all_urls>"],
main() {
browser.runtime.onMessage.addListener((message, _, sendResponse: (response?: any) => void) => {
someAsyncWork(message,sendResponse);
return true;
});
},
}); Now that I know we can return a response without |
Feature Request
If we do not use
webextension-polyfill
, whenbrowser.runtime.onMessage
in a content script receives a message from a popup page etc. and returns a response, a Chrome extension needs to use a listener function's argumentsendResponse
.However, a Firefox extension needs to return the response as the return value of the listener function.
Accoding to Upgrade Guide, in in v0.20.0,
webextension-polyfill
is removed.If so, I would like the way responses are returned to be unified between Chrome and Firefox extensions.
Is your feature request related to a bug?
N/A
What are the alternatives?
webextension-polyfill
if our extensions usebrowser.runtime.onMessage
Additional context
webextension-polyfill
by default #784The text was updated successfully, but these errors were encountered: