Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Post a Comment for "Catch If Runtime.sendMessage Doesn't Receive Response"