chrome浏览器插件的background.js中处理的数据是空

发布于:

#浏览器插件开发踩坑:Background fetch 返回空对象问题

#问题描述

在开发浏览器插件时遇到一个常见问题:在 background.js 中使用 fetch 调用服务端接口,虽然接口正常返回数据,但在 content script 或 popup 等外部 JS 文件中通过消息传递收到的却是空对象。

#问题原因

因为 fetch 的 then 后没有转换为 json 对象,导致外部 JS 无法获取到数据。
在经过 background.js 中发送消息给外部 JS 文件时,fetch 的数据如果不是 json 数据,那么外部 JS 文件将无法获取到数据,只能收到一个空对象。
javascript
// ❌ 错误示例 chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { fetch('https://api.example.com/data').then(data => { sendResponse(data) // 异步回调,此时消息通道已关闭 }) return true })

#解决方案

#在 background.js 中直接把 fetch 到的数据转换成 json 数据

javascript
// ✅ 正确示例 chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { fetch('https://api.example.com/data') .then(res => res.json()) .then(data => { sendResponse(data) }) return true })

#关键要点

  1. 必须返回 true: 告诉浏览器你将异步调用 sendResponse
  2. fetch 的 then 后必须转换为 json 对象

#外部调用示例

javascript
// content.js 或 popup.js chrome.runtime.sendMessage({ action: 'fetchData' }, response => { console.log('接收到数据:', response) })