jhen0409 / react-chrome-extension-boilerplate

Boilerplate for Chrome Extension React.js project
MIT License
2.14k stars 388 forks source link

Add messaging example #77

Closed hakunin closed 6 years ago

hakunin commented 6 years ago

Hi, I've been trying to add messaging from the injected script to a dev panel aaaaand the learning curve is pretty steep.

It might be a great addition to add messaging, since I've seen people struggling with it on stack overflow as well.

I haven't been able to pass a message from injected script yet.

hobofan commented 6 years ago

What part were you struggling with?

The example at https://developer.chrome.com/extensions/messaging works without problems for me.


Place at the bottom of extension/background/inject.js:

chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

In a React component, e.g. the constructor of InjectApp in extension/inject.js:

chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});
hakunin commented 6 years ago

Thanks, I've been able to find a way to do it after a week of researching the topic on stackoverflow.