【问题标题】:Send message from content script to another从内容脚本向另一个发送消息
【发布时间】:2018-04-29 00:54:54
【问题描述】:

我正在开发一个谷歌浏览器扩展。我的目的是将消息从我的 script1.js 发送到 script2.js。这是我在 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 中写的:

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

在 script2.js 中:

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

警报(响应);

});

我不认为我正在以写入方式进行操作,我认为我必须使用 background.js,但我不知道如何。

非常感谢。

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension


    【解决方案1】:

    正如你所说,你必须使用后台脚本。例如:

    脚本1:

    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"});
    

    记得在清单中包含你的后台脚本:

    "background": {
        "scripts": ["background.js"]
    }
    

    【讨论】:

    • @FlorianBirolleau 我已经编辑了代码以显示一种可能的方式来识别选项卡。
    • 您有获取当前标签 ID 的代码吗?我正在尝试将消息从另一个 script3 发送到 script1,但它没有到达 script1,但它进入了 background.js。干杯
    猜你喜欢
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2014-07-03
    • 2014-02-04
    • 2021-08-02
    相关资源
    最近更新 更多