content向background发送消息的异步返回

背景:
    content向background发送消息后,没有等到background执行完毕直接进行了sendResponse返回,导致content拿不到background处理后的数据集。

    下面需要做的就是,content监听background执行,能异步拿到background执行结果。只需要在onMessage的时候进行一个return true 就可以了。

content向background发送消息后的异步消息返回
popul与content & background的消息通信这里不描述,异步消息的处理方式是相同的

// content.js
// content给后台发送消息
function sendMessageToBackground(msg, callback) {
  chrome.runtime.sendMessage(msg, (response) => {
    if(callback) {
      callback(response)
    } 
  })
}

// content发送消息并等待消息返回
sendMessageToBackground({type: 'xxx'}, (response) => {
	console.log(response)
})

重点关注一下backgroun接收到消息后的异步返回处理

// background.js
// background 接收到消息后处理
function getMessage(handler) {
  if(handler) {
    chrome.runtime.onMessage.addListener((request, render, sendResponse) => {
      handler(request, render, sendResponse)
      return true // 重点是这一个 返回true:允许返回异步消息
    })
  }
}

// background 接收到消息后的处理
getMessage((request, render, sendResponse) => {
  // 假设去掉return ture后,放开下面代码,是会返回ok还是result?
  // sendResponse('ok')
  if(request.type === 'xxx') {
    // 一些异步消息的处理
    // 假设在handler回调之后没有做 return ture; 处理?而且该代码块是一段时间较长异步操作,sendResponse()返回将会报错,不能正确返回到调用处
    sendResponse('reslut')  // 因为return true;这里可以异步处理消息后返回
  }
})

关于chrome.runtime.onMessage.addListener监听消息的异步返回找了很长时间才在官网找到相关描述。

chrome runtime API 相关描述
chrome extension 官网关于异步消息返回描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小白说(๑• . •๑)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值