0

I have a chrome extension I'm working on. My background.js script does something and returns a string (backgroundResponse) back to my content_script.js. This works fine as shown here:

webpage (index.html):

jQuery("#clickmenow").on("click", function (event)
{
   document.dispatchEvent(new CustomEvent('funcDoRequest', {
      'detail': { task: 'dir' }
   }));

   // I want backgroundResponse here instead somehow..?
});
<a href="#" id="clickmenow">Click me now</a>

background.js

document.addEventListener("funcDoRequest", function (stuff)
{
    chrome.runtime.sendMessage(stuff.detail, function (backgroundResponse)
    { alert('Returning data from background.js: ' + backgroundResponse); });
});

My problem is I would like the response backgroundResponse to be returned synchronously to the calling jQuery on click somehow. So when someone clicks #clickmenow it ends up running my background.js stuff, and returns the value all the way back to the onclick (or dispatchEvent), not just to content_script.js which is what it is doing now. How can I do this? I can't figure it out.

Xan
  • 74,770
  • 16
  • 179
  • 206
Ken Williams
  • 829
  • 1
  • 10
  • 20

2 Answers2

0

I would like the response backgroundResponse to be returned synchronously

That's not going to be possible - any communication with the background page is going to involve async messaging.


Event-based communication can't use explicit responses, but you can just as well trigger another event that the page listens to. You can include some sort of unique ID that the content script must copy to the response to differentiate between events.


Finally, if that's a webpage you control on a domain you know in advance, consider using externally_connectable and speaking to the background page directly.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206
-1

both content script and background page can use chrome.runtime.sendMessage api to communicate

//content script
jQuery("#clickmenow").on("click", function (event) {
    chrome.runtime.sendMessage({'detail': { task: 'dir' }}, function (backgroundResponse) { alert('Returning data from background.js: ' + 
       // handle backgroundResponse
    });

});


//background page

  chrome.runtime.onMessage.addListener(function(detailFromContentScript, sender, sendResponse) {
    // handle detailFromContentscript
    var backgroundResponse = process(detailFromContentScript)

    // then send back response to content script
    sendResponse(backgroundResponse)
})
ginotria
  • 303
  • 2
  • 9