chrome extension sendmessage async

遇到的问题:

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

解决思路和方法:

google 找到的解决方法:

https://stackoverflow.com/questions/14094447/chrome-extension-dealing-with-asynchronous-sendmessage

  • 关键代码(解决我问题的答案,来自链接网页)
javascript 复制代码
// 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 改造一下就可以了。
javascript 复制代码
// 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异步函数技术编写相关代码
相关推荐
小猪努力学前端8 分钟前
基于PixiJS的小游戏广告开发
前端·webgl·游戏开发
哆啦A梦158813 分钟前
62 对接支付宝沙箱
前端·javascript·vue.js·node.js
Tzarevich24 分钟前
用 OOP 思维打造可复用的就地编辑组件:EditInPlace 实战解析
javascript·前端框架
用户81686947472525 分钟前
Lane 优先级模型与时间切片调度
前端·react.js
虎头金猫26 分钟前
MateChat赋能电商行业智能导购:基于DevUI的技术实践
前端·前端框架·aigc·ai编程·ai写作·华为snap·devui
LiuMingXin26 分钟前
CESIUM JS 学习笔记 (持续更新)
前端·cesium
豆苗学前端35 分钟前
面试复盘:谈谈你对 原型、原型链、构造函数、实例、继承的理解
前端·javascript·面试
Crystal3281 小时前
Git 基础:生成版本、撤消操作、版本重置、忽略文件
前端·git·github
lichenyang4531 小时前
React 组件通讯全案例解析:从 Context 到 Ref 的实战应用
前端
国服第二切图仔1 小时前
Electron for 鸿蒙pc项目实战之右键菜单组件
javascript·electron·harmonyos·鸿蒙pc