当前位置: 首页 > article >正文

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异步函数技术编写相关代码

http://www.kler.cn/a/280182.html

相关文章:

  • http应用层协议
  • 2024年高校辅导员考试题库及答案
  • 国产游戏技术能否引领全球
  • 鸿蒙位置服务
  • 秒开WebView?Android性能优化全攻略
  • Composio:开源项目中的AI智能体任务执行利器
  • 【pycharm】汉化及翻译插件
  • 深入理解 Go 语言并发编程--管道(channel) 的底层原理
  • 百度搜索的RLHF性能优化实践
  • 14.JS学习篇-CSR和SSR
  • 深入理解Spring Boot中的@ConditionalOnProperty注解及其应用
  • 【书生大模型实战营(暑假场)】进阶任务三 LMDeploy 量化部署实践闯关任务
  • 深度学习100问10-什么是CBOW模型
  • 后端开发刷题 | 合并k个已排序的链表
  • Docker常见命令和参数
  • 2、LVGL控件-标签、按钮
  • uni-app开发日志:schema2code生成的新增页和修改页因字段太多用分段器实现分段分类
  • abc 366 E+F(曼哈顿距离 x y 两个坐标分别计算)(贪心+01背包)
  • 微前端架构:使用不同框架构建可扩展的大型应用
  • Pytest框架直接右键运行 testcase.py,不执行最外层conftest