Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send message from content script to another

I am developping a google chrome extension. My purpose is to send message 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 write way, i think i've to use the background.js but i don't know how.

Thanks very much in advance.

like image 525
Florian Birolleau Avatar asked Nov 15 '17 17:11

Florian Birolleau


People also ask

How do you communicate between content scripts?

Communicating with the web page By default, content scripts don't get access to the objects created by page scripts. However, they can communicate with page scripts using the DOM window. postMessage and window. addEventListener APIs.

How can background scripts and content scripts communicate?

Communication between extensions and their content scripts works by using message passing. Either side can listen for messages sent from the other end, and respond on the same channel. A message can contain any valid JSON object (null, boolean, number, string, array, or object).

What is unchecked runtime lastError?

The runtime. lastError property is set when an asynchronous function has an error condition that it needs to report to its caller. If you call an asynchronous function that may set lastError , you are expected to check for the error when you handle the result of the function.


1 Answers

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"]
}
like image 133
Iván Nokonoko Avatar answered Sep 19 '22 16:09

Iván Nokonoko