chrome-types icon indicating copy to clipboard operation
chrome-types copied to clipboard

Update runtime/tabs.sendMessage types to include callback

Open mp3por opened this issue 1 year ago • 3 comments

As per documentation of runtime.sendMessage and tabs.sendMessage the methods have a 4th parameter callback. At the moment this parameter is missing from the types and typescript complains.

image

mp3por avatar Jan 04 '24 21:01 mp3por

@mp3por temp solution described here

UPD: I haven't noticed that you referencing Promise based version. So this one is correct, there's also overload with callback version.

image

yellott avatar Feb 22 '24 10:02 yellott

@mp3por temp solution described here

UPD: I haven't noticed that you referencing Promise based version. So this one is correct, there's also overload with callback version.

image

I did not understand your EDIT. How to reference the correct type ?

mp3por avatar Mar 01 '24 05:03 mp3por

@mp3por Sorry, I didn't explain clearly. So if you don't need/want to use Promise version of sendMessage you have two options:

  1. Explicitly pull desired type from provided type definitions by matching the overload, like so:
chrome.runtime.sendMessage({ type: "MessageType" }, undefined, (response) => {
  console.log("response", response);
});
  1. Since the documentation states that the options parameter is optional (yet there is no overload for cases where the callback is the second/third parameter, even though it is entirely legal according to my tests), you can extend the default types so that the callback can be passed as the second or third parameter, like so:
// Path: src/global.d.ts

declare namespace chrome {
  /// <reference types="chrome-types" />
  export namespace runtime {
    export function sendMessage(
      extensionId: string,

      message: any,

      callback?: (response: any) => void,
    ): void;

    export function sendMessage(
      message: any,

      callback?: (response: any) => void,
    ): void;
  }
}

UPD: After adjusting types you'll be able to call sendMessage like this:

chrome.runtime.sendMessage({ type: "MessageType" }, (response) => {
  console.log("response", response);
});

For simplicity I've only showed example for chrome.runtime.sendMessage but the same can be applied to chrome.tabs.sendMessage. Let me know if this is clear or any further help is required.

yellott avatar Mar 01 '24 06:03 yellott