0

I am working connect a Chrome extension with a background script. For simple synchronous calls it works fine. I send a message and get a response.

Apparently, the below getValue, which internally uses IndexedDB with Dexie promises, does not allow to use the simple sendResponse. I saw the way to deal with this would be to send message in response. However, for me, it does not really make sense. The background script simply checks whether the value a specific key is to be found in the database. Extension should just block until the value for the key is returned.

Could I unroll this somehow to use sendResponse? Perhaps wrap return findData() into a synchronous function?

chrome.runtime.sendMessage({
  request:'getValue',
  key: shortcutKey
}, (data) => {
  debugLog('getShortcut:', data);
  let value = data.value;
  console.log(`for key: ${key} found ${value}`);
  ...
  do_my_thing();
});

Background script:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  switch (request.name) {
    case 'getClipboard':
      sendResponse({clipboard:getClipboard()});
      break;
    case 'getValue':
      console.log(`background::getValue handler key:`, request.key);
      return findData(request.key.substring(constants.PREFIX.length)).then((result) => {
        console.log(`findData return: ${result}`);
        sendResponse( { value: result });
      });
      break;
      ...
  }
});
Makyen
  • 31,849
  • 12
  • 86
  • 121
Moshe Shmukler
  • 1,270
  • 2
  • 21
  • 43

1 Answers1

4

Just return true in asyncronius cases!

Note: The sendResponse callback is only valid if used synchronously, or if the event handler returns true to indicate that it will respond asynchronously. The sendMessage function's callback will be invoked automatically if no handlers return true or if the sendResponse callback is garbage-collected. https://developer.chrome.com/apps/messaging

Rafael Hovsepyan
  • 781
  • 8
  • 14