从内容脚本发送消息到另一个 [英] Send message from content script to another

查看:67
本文介绍了从内容脚本发送消息到另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发google chrome扩展程序.我的目的是将消息从script1.js发送到script2.js.这是我在manifest.json

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

  },

这是我在script1.js中写的内容:

Here is what i wrote in script1.js:

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

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

以及在script2.js中:

and in script2.js:

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

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

警报(响应);

});

我不认为我是以写方式进行操作,我认为我必须使用background.js,但我不知道该怎么做.

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.

非常感谢.

推荐答案

正如您所说,您必须使用后台脚本.例如:

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

脚本1:

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

background.js

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

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

这篇关于从内容脚本发送消息到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆