最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Send message from content script to another - Stack Overflow

programmeradmin4浏览0评论

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": ["/"],
    "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.

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.

Share Improve this question edited Jan 14, 2023 at 11:25 Lerner Zhang 7,1302 gold badges58 silver badges79 bronze badges asked Nov 15, 2017 at 17:14 Florian BirolleauFlorian Birolleau 3434 silver badges17 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

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"]
}
发布评论

评论列表(0)

  1. 暂无评论