Send message from content script to another

北战南征 提交于 2020-08-05 02:03:55

问题


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.


回答1:


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"]
}


来源:https://stackoverflow.com/questions/47313507/send-message-from-content-script-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!