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.
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.
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).
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.
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"]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With