如何在两个Chrome应用程序之间传递数据?

问题描述:

我已经创建了两个Chrome应用程序,我希望将某个数据(字符串格式)从一个Chrome应用程序传递到另一个Chrome应用程序。感谢有人能帮助我展示正确的做法吗?如何在两个Chrome应用程序之间传递数据?

这是一个RTFM问题。

Messaging documentation(请注意,它提到的扩展,但它适用于应用程序):

除了在扩展发送不同组件之间的消息,您可以使用消息API与其他扩展进行通信。这使您可以公开其他扩展可以利用的公共API。

您需要使用chrome.runtime.sendMessage(使用应用程序ID)发送消息并使用chrome.runtime.onMessageExternal事件接收它们。如果需要,还可以建立长期连接。

// App 1 
var app2id = "abcdefghijklmnoabcdefhijklmnoab2"; 
chrome.runtime.onMessageExternal.addListener(
    // This should fire even if the app is not running, as long as it is 
    // included in the event page (background script) 
    function(request, sender, sendResponse) { 
    if(sender.id == app2id && request.data) { 
     // Use data passed 
     // Pass an answer with sendResponse() if needed 
    } 
    } 
); 

// App 2 
var app1id = "abcdefghijklmnoabcdefhijklmnoab1"; 
chrome.runtime.sendMessage(app1id, {data: /* some data */}, 
    function(response) { 
    if(response) { 
     // Installed and responded 
    } else { 
     // Could not connect; not installed 
     // Maybe inspect chrome.runtime.lastError 
    } 
    } 
); 
+0

感谢您的指导Xan。 – adw 2014-11-17 10:48:22