You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展开发:如何将ArrayBuffer转换为JSON及处理请求Payload

Hey there! Let's figure out how to convert that ArrayBuffer into your desired JSON format for your Chrome extension. Here's a straightforward approach that should work perfectly:

Step 1: Decode the ArrayBuffer to a String

First, your ArrayBuffer is holding binary data that's likely encoded in UTF-8 (the standard for web text payloads). We can use the browser's built-in TextDecoder API to convert this binary buffer into a regular string:

const decoder = new TextDecoder('utf-8');
const crawlerInfoText = decoder.decode(yourArrayBuffer);

This will take the raw binary data from your ArrayBuffer and turn it into the long string you need for the crawlerInfo field.

Step 2: Construct the Target JSON Object

Once you have the decoded string, simply wrap it into the JSON structure you specified:

const targetJson = {
  crawlerInfo: crawlerInfoText
};

// If you need the JSON as a string (e.g., for logging or sending elsewhere), use:
const targetJsonString = JSON.stringify(targetJson);

Full Working Example

Putting it all together, here's a reusable function you can drop into your extension:

function transformBufferToCrawlerJson(requestBuffer) {
  // Decode ArrayBuffer to UTF-8 string
  const textDecoder = new TextDecoder('utf-8');
  const crawlerString = textDecoder.decode(requestBuffer);
  
  // Build and return the target JSON (object or string)
  const result = { crawlerInfo: crawlerString };
  return JSON.stringify(result); // Remove JSON.stringify if you want the object instead
}

// Usage:
const payloadBuffer = // Your fetched ArrayBuffer here
const finalJson = transformBufferToCrawlerJson(payloadBuffer);
console.log(finalJson); // Will log the exact JSON format you need

Quick Notes

  • Encoding Check: Double-check that your payload is indeed UTF-8 encoded. If it uses a different encoding (like ASCII), just update the TextDecoder parameter (e.g., new TextDecoder('ascii')).
  • Binary Data Edge Case: If your ArrayBuffer contains non-text binary data, this approach won't work—but based on your example, it looks like you're dealing with a plain text string payload, so this should be fine.

内容的提问来源于stack exchange,提问作者天气君

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:35:44