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异步函数技术编写相关代码
相关推荐
九九落18 分钟前
前端获取经纬度完全指南:从Geolocation API到地图集成
前端·获取经纬度
来恩100332 分钟前
jQuery选择器
前端·javascript·jquery
前端繁华如梦34 分钟前
树上挂苹果还是挂玻璃球?Three.js 程序化果实的完整实现指南
前端·javascript
墨痕诉清风41 分钟前
Web浏览器客户端检测网站网络健康(代码)
前端·网络·测试工具
IMPYLH43 分钟前
Linux 的 wc 命令
linux·运维·服务器·前端·bash
happybasic1 小时前
Python库升级标准流程~
linux·前端·python
川冰ICE1 小时前
前端工程化深度实战:从Webpack5到Vite5的构建工具演进与选型决策
前端
CDwenhuohuo1 小时前
优惠券组件直接用 uview plus
前端·javascript·vue.js
用户74090472362751 小时前
我用 curl 排查了一次 OpenAI-compatible API 连接失败:401、403、404 分别怎么定位
前端
kft13141 小时前
XSS深度剖析:从弹窗到持久化窃取Cookie
前端·web安全·xss·安全测试