2014-10-07 51 views
0

我的场景是我打开了一个浏览器,并打开了多个选项卡,并在选项卡上向后台发送消息。然后从后台我想发送一条消息回发送原始邮件的选项卡。如何将消息传递回特定的选项卡?

我试过使用appAPI.message.toActiveTab,但并不总是工作,因为用户可以在后台发送消息之前更改选项卡。 Crossrider有没有办法实现这一点?

回答

1

您可以通过将tabId作为请求的一部分传递给后台代码来实现您的目标。在后台中,向所有选项卡广播响应并在消息中发送tabId,以便原始选项卡可以识别该消息。

下面的例子说明的原理是:

extension.js

appAPI.ready(function($) { 
    // Listener to handle incoming messages 
    appAPI.message.addListener(function(msg) { 
    // Check if the message is intended for this tad 
    if (msg.tabId === appAPI.getTabId()) { 
     // Your code here 
    } 
    }); 

    // Send message to background 
    appAPI.message.toBackground({ 
    // Pass the tabId with the message 
    tabId: appAPI.getTabId(), 
    yourData: ... 
    }); 
}); 

background.js

appAPI.ready(function($) { 
    // Listener to handle incoming messages 
    appAPI.message.addListener(function(msg) { 
    // Send message to all tabs 
    appAPI.message.toAllTabs({ 
     // Pass the tabId with the message to identification 
     tabId: msg.tabId, 
     yourData: ... 
    }); 
    }); 
}); 

[披露:我是Crossrider员工]

相关问题