简体   繁体   English

从chrome扩展程序向chrome应用发送消息

[英]Send message from chrome extension to chrome app

I am developing a test app for chrome. 我正在为Chrome开发一个测试应用程序。

I also am developing an extension, which should get tab url and send a message to the app with the url of the tab, where the extension was activated. 我还正在开发一个扩展程序,该扩展程序应获取tab url并使用tab url将消息发送到应用程序,其中扩展程序已被激活。

In the extension I have this background.js 在扩展名中我有这个background.js

chrome.browserAction.onClicked.addListener(function(tab) {
    alert(tab.url);
});

the tab.url info is correct, I need to send to the app, (which also is in javascript). tab.url信息正确,我需要发送到应用程序(也在javascript中)。

I have read many examples on internet, but there is something I'm not getting. 我已经在互联网上阅读了许多示例,但有些东西我没有得到。 How should I post the message, and how to listen on the app for that message? 我应该如何发布消息,以及如何在应用程序上收听该消息?

Messaging docs have a clear example . 消息传递文档有一个明确的示例

Extension code: 扩展代码:

chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.runtime.sendMessage("appIdHere", {tabUrl: tab.url});
});

App code: 应用程式码:

chrome.runtime.onMessageExternal.addListener(
    function(message, sender, sendResponse) {
        // Check the ID! Requests may be spoofed.
        if(sender.id == "extensionIdHere" && message.tabUrl) {
            doStuff(message.tabUrl);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM