chrome extension sendmessage async

遇到的问题:
Chrome 插件开发,需要实现 content 页面使用 chrome.runtime.sendMessage 发送消息给 background,background 需要异步处理完消息以后再发送处理结果给content 页面。

解决思路和方法:
google 找到的解决方法:
https://stackoverflow.com/questions/14094447/chrome-extension-dealing-with-asynchronous-sendmessage

  • 关键代码(解决我问题的答案,来自链接网页)
// content.js
chrome.runtime.sendMessage({ type: "GET_FOO" }, function (response) {
  console.log(response.foo);
});


// background.js
// replace with a real call that
// needs to run asynchronously
async function getFoo() {
  return "bar"
}

async function sendFoo(sendResponse) {
  const foo = await getFoo()
  sendResponse({ foo })
}

chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
    if (request.type === "GET_FOO") {
      sendFoo(sendResponse)
      return true
    }
  }
);
  • 直接使用到我项目里面时,发现还需要修改(为了方便阅读,我直接在上面的代码中进行修改):代码中 getFoo 函数部分,我需要通过 $.ajax 发送一个异步请求,那么直接用 await getFoo() 就达不到效果,使用 promise 把 getFoo 改造一下就可以了。
// content.js
chrome.runtime.sendMessage({ type: "GET_FOO" }, function (response) {
    console.log(response.foo);
});

// background.js
//reqParams是请求参数
function getFoo(reqParams) {
    return new Promise((resolve, reject) => {
        //模拟发送ajax请求结果
        if (true) {
            resolve("success")
        } else {
            resolve("fail")
        }
    });
}

async function sendFoo(sendResponse, reqParams) {
    const foo = await getFoo(reqParams)
    sendResponse({ foo })
}

chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if (request.type === "GET_FOO") {
            const reqParams = { param1: '1', param2: '2' }
            sendFoo(sendResponse, reqParams)
            return true
        }
    }
);

这些是解决问题的思路,重点是:

  • chrome.runtime.onMessage.addListener 中 return true
  • 使用JS异步函数技术编写相关代码
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值