我的场景是,我打开了一个浏览器,打开了多个选项卡,其中一个选项卡向后台发送了一条消息。然后,我想从后台将一条消息发送回发送原始消息的选项卡。
我尝试过使用appAPI.message.toActiveTab,但这并不总是有效,因为用户可以在后台发送消息之前更改选项卡。有没有办法用Crossrider实现这一点?
发布于 2014-10-07 22:57:19
您可以通过将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员工
https://stackoverflow.com/questions/26237539
复制相似问题