yegorchik
yegorchik

Reputation: 179

Catch if runtime.sendMessage doesn't receive response

Let's say we have a background script which communicates with the browser action popup.

Under certain conditions I want to send a message to popup. First, I need to get if popup is opened at all (where chrome.extension.getViews({ type: "popup" }) can be used). Secondly, I want to send a message to that popup. The problem is that I want to place the runtime.onMessage listener in the popup only after certain async tasks, therefore what we'll get is that if the popup is opened and we will try to send a message there, it will produce an error since runtime.sendMessage method will try to send a message to the unset (yet) runtime.onMessage listener.

I couldn't find a way to catch that error because of the way it is handled in chrome API. Basically what I want is to be able to catch an error if I'm trying to send a message to the unset runtime.onMessage listener.

Upvotes: 0

Views: 1164

Answers (1)

woxxom
woxxom

Reputation: 73826

It should be possible to catch the error by checking chrome.runtime.lastError inside the callback of sendMessage:

chrome.runtime.sendMessage('foo', data => {
  if (chrome.runtime.lastError) {
    console.log('Yay');
  } else {
    // use data
  }
});

P.S. you probably don't need to use extension messaging when communicating between two extension pages such as the background script and the popup script because it's slow (it serializes to JSON internally). You can directly access the background script's window object and its global variables by using chrome.runtime.getBackgroundPage or chrome.extension.getBackgroundPage in the popup script. You can also use BroadcastChannel API which utilizes the fast structured cloning algorithm that's capable of transferring a lot more object types than the JSON-based extension messaging.

Upvotes: 4

Related Questions