javascript - Crossrider 浏览器扩展 : Bidirectional communication between frontend and background

标签 javascript message javascript-framework crossrider

我正在使用 crossrider.com 编写一个可移植浏览器扩展。

我的扩展由前端部分(crossrider:扩展页面范围)和后端部分(crossrider:后台范围)组成。后台在每个浏览器上运行一次,前端在每个站点调用上运行一次。

我的后端提供了前端调用的函数。 Crossrider 为此提供了消息 API。

前端现在想要请求一些数据,后端应该返回它。我选择的方式是:

后端:

appAPI.message.addListener({channel:"functionname"},function(returnval) {
    //Calculate some value v
    appAPI.message.toActiveTab(v, {channel:"functionname_returnval"});
});

前端:

appAPI.message.addListener({channel:"functionname_returnval"}, function(message) {
    //Do something with the return value
});
appAPI.message.toBackground(message,{channel:"functionname"});

这有效,但前提是用户同时不切换选项卡。不幸的是,appAPI.message.toActiveTab 不会将答案发送到调用后台函数的选项卡,而是发送到当前打开的选项卡 - 在此期间这可能已更改。

如何将响应发送到调用后台函数的选项卡?

最佳答案

您可以按如下方式解决该问题(有点像以太网协议(protocol)):

  1. 前端:将选项卡的 ID 包含到发送到后端的消息
  2. 后端:将响应广播到所有选项卡,并在消息中包含收到的选项卡 ID
  3. 前端:只有具有匹配选项卡 ID 的选项卡才会处理响应

因此,使用您的代码作为基础,解决方案如下:

后端:

appAPI.message.addListener({channel:"functionname"}, function(returnval) {
    //Calculate some value v
    appAPI.message.toAllTabs({tabId:returnval.tabId,rv:v}, {channel:"functionname_returnval"});
});

前端:

appAPI.message.addListener({channel:"functionname_returnval"}, function(message) {
    // Check if message is for this tab
    if (message.tabId === appAPI.getTabId()) {
        //Do something with the return value (message.rv)
    }
});
appAPI.message.toBackground({tabId:appAPI.getTabId(), ...},{channel:"functionname"});

免责声明:我是 Crossrider 员工。

关于javascript - Crossrider 浏览器扩展 : Bidirectional communication between frontend and background,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19273351/

相关文章:

javascript - HTML5 : Whenever I send a text area message to fill out the body of an email the name of the text area proceeds it. 如何修复此问题?

java - 如何通过其他浏览器将文本写入Gmail邮件正文

javascript - 下拉 currentIndex onchange

javascript - 如何创建带有两个 div 的列,其中一个固定在第二个上方,滚动时隐藏在第一个后面?

Django 覆盖默认表单错误消息

javascript - 在 angularjs 中使用 $sce 或 Strict Contextual Escaping 有什么好处,为什么 React 不需要这样做?

javascript - 如何在 JQuery 中选择除被单击元素之外的所有类?

javascript - 最初加载时 C3 图表尺寸太大

javascript - 在 Azure 移动服务自定义 API 中使用事务

javascript - VueJS 自定义 Prop 验证功能