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异步函数技术编写相关代码
相关推荐
Asize4 分钟前
前端接口工程:axios + mock,前端不再傻等后端
前端·javascript
结网的兔子4 分钟前
【前端开发】UniApp 项目地图选型与Web-APP跨端迁移方案
前端·uni-app
张元清4 分钟前
React useElementSize Hook:用 ResizeObserver 实时追踪元素宽高 (2026)
javascript·react.js
Canace8 分钟前
给 Claude 一个链接,它真的读了原文吗
前端·人工智能·ai编程
爱丶不疚9 分钟前
Electron net 模块你可以没用过,但不能不知道
前端·electron
cidy_9810 分钟前
React + Ant Design 通用企业数据统计模块实战
前端
渣波13 分钟前
React 性能优化与状态管理双雄:useMemo 与 useReducer 深度解析
前端·javascript
Maxkim14 分钟前
把智能体塞进浏览器侧边栏:我在 MV3 里踩的 5 个坑
前端·后端
渣波15 分钟前
告别 LLM 幻觉:用 Harness 工程化思维打造生产级 AI 应用
前端·javascript
breeze jiang33 分钟前
React Todos 前端独立开发全解:用 vite-plugin-mock + axios 封装,再也不等后端接口
前端·react.js·状态模式