user3647376
user3647376

Reputation: 91

Chrome extension - pass function result from content script to popup.js

I have extension with popup.html which has popup.js in it. I use popup.js to call function located in content script using chrome.tabs.sendMessage -method. This is working nicely, but..

How do I return the value of the function back to popup.js ? Do I need to set up a listener on the popup.js aswell or what ?

On my popup.js I have:

chrome.tabs.sendMessage(tab.id, {
 expiryRequest: 'expiry '
}, function (response) {
if (response.refreshResponse === true) {
 console.log('Expiry taken');
} else {
 console.log('Expiry NOT taken');
}
});

This part works great..

On my content script I read certain div into a vartiable "result". At the end of the function on content script I have used.

return result;

or

return true;

None of those returns anything back tuo popup.js. What do I need to change in order to get my return to work from content script to popup.js ?

Upvotes: 1

Views: 1809

Answers (1)

Xan
Xan

Reputation: 77591

You should not return your result, but send it back.

chrome.runtime.onMessage callbacks take 3 parameters: the message, the sender information, and the sendResponse callback.

To pass a response back, sendResponse must be called:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
  if(message.ping) sendResponse({pong: true});
});

However, there's an additional trick to it. The event listener should either reply immediately (i.e. synchronously, before it exits) or signal that it will reply later. This is done with the return value:

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse){
  if(message.ping) {
    chrome.storage.local.get("shouldReply", function(result){
      // This is asynchronous: by now the listener returned
      if(result.shouldReply) sendResponse({pong: true});
    });
  }
  return true; // Indicate that you will eventually call sendResponse
});    

Unless you do this, sendResponse reference is invalidated when the listener exits and an undefined response is sent.

One more caveat: you should call sendResponse no more than once; it will generate an error otherwise.

Upvotes: 3

Related Questions