10

I am developing a Google chrome extension. My purpose is to send messages from my script1.js to script2.js. Here is what I wrote in my manifest.json:

  {
    "matches": ["https://www.google.fr/"],
    "css": ["styles.css"],
    "js": ["script1.js"]
       
  },
  {
    "matches": ["my_website.html"],
    "css": ["styles.css"],
    "js": ["script2.js"]
       
  },

Here is what I wrote in script1.js:

chrome.runtime.sendMessage('hello world!!!!!!');

and in script2.js:

chrome.runtime.onMessage.addListener(function(response,sender,sendResponse){

alert(response);

} );

I don't think I'm doing it the right way, I think I've to use the background.js but I don't know how.

Thanks very much in advance.

Lerner Zhang
  • 6,184
  • 2
  • 49
  • 66

1 Answers1

12

As you say, you have to use background script. For example:

script1:

chrome.runtime.sendMessage({from:"script1",message:"hello!"});

background.js

var tab2id;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    if (message.from == "script2") {
        tab2id = sender.tab.id;
    }
    if (message.from == "script1"){
        chrome.tabs.sendMessage(tab2id,message);
    }
});

script2.js

chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
    alert("Script1 says: " + message.message);
});
chrome.runtime.sendMessage({from:"script2"});

Remember to include your background script in manifest:

"background": {
    "scripts": ["background.js"]
}
Iván Nokonoko
  • 4,888
  • 2
  • 19
  • 27
  • 1
    @FlorianBirolleau I've edited the code to show one possible way to identify the tabs. – Iván Nokonoko Nov 15 '17 at 19:19
  • Would you have a code to get the current tabs ID ? I'm trying to send message from another script3 to script1 and it doesn't reach script1 but it goes into the background.js. Cheers – Florian Birolleau Nov 16 '17 at 17:16