chrome.runtime.onMessage response with async await

后端 未结 4 1804
闹比i
闹比i 2021-02-05 04:03

I want to use async await in an onMessage listener:

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) =>{
    var key = await getKey(         


        
4条回答
  •  渐次进展
    2021-02-05 04:33

    Not sure if Chrome extension runtime environment supports the async/await syntax, but you can use a transpiler (i.e. Babel) to have it converted to for example ES5. Then you can define a wrapper function like this:

    function asChromeListener(listener) {
      return (message, sender, sendResponse) => {
        const returnValue = listener(message, sender);
    
        if (isPromise(returnValue)) {
          returnValue.then(sendResponse);
          return true;
        }
        else {
          if (typeof returnValue !== 'undefined') {
            sendResponse(returnValue);
          }
          return false;
        }
      };
    }
    
    function isPromise(value) {
      return typeof value === 'object' && value !== null && 'then' in value && 'catch' in value;
    }
    

    Which you can then use like:

    chrome.runtime.onMessage.addListener(asChromeListener(async (message, sender) => {
      return await doMyAsyncWork(message);
    });
    

    Since we use TypeScript, here's also the snippet that we actually use (with generic types).

    export function asChromeListener(listener: (message: M, sender: S) => any) {
      return (message: M, sender: S, sendResponse: R) => {
        const returnValue = listener(message, sender);
    
        if (isPromise(returnValue)) {
          returnValue.then(sendResponse);
          return true;
        }
        else {
          if (typeof returnValue !== 'undefined') {
            sendResponse(returnValue);
          }
          return false;
        }
      };
    }
    
    function isPromise(value: any) {
      return typeof value === 'object' && value !== null && 'then' in value && 'catch' in value;
    }
    

提交回复
热议问题