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

如何理解GM_xmlhttpRequest的binary参数?测试发现不同取值发送数据一致

Understanding the binary Parameter in GM_xmlhttpRequest

Great question—your test results make total sense once you clarify what the binary parameter actually does (it’s easy to assume it affects request data, but that’s not its main job!). Let’s break this down:

First: Why Your Test Requests Show No Difference

The binary parameter doesn’t change how request data is sent—here’s why your two test cases looked identical in Fiddler:

  • When your data is a string (like "a1b2"): Greasemonkey/Tampermonkey will always encode the string to bytes using UTF-8 (the standard for HTTP requests) regardless of the binary setting. So whether you set binary: true or false, the raw byte stream sent to the server is exactly the same.
  • When your data is a Blob (like new Blob([1,2,3])): Blobs are already raw binary data. GM_xmlhttpRequest just sends the blob’s bytes directly, so the binary flag has no impact on the outgoing request here either.

The Real Purpose of binary: Handling Responses

The binary parameter’s core role is controlling how response data is parsed when it comes back from the server:

  • binary: false (default): The response is treated as text. GM_xmlhttpRequest will attempt to decode the raw bytes into a string using the character encoding specified in the response’s Content-Type header (or UTF-8 if none is set). This is ideal for JSON, HTML, or plain text responses.
  • binary: true: The response is kept as raw binary data (usually returned as a Uint8Array or Blob, depending on the userscript engine). This is critical for handling non-text resources like images, PDFs, or any file where you need the exact byte stream instead of a decoded string.

Example: Using binary for Binary Responses

Here’s a practical use case where binary makes all the difference—fetching an image and displaying it in the page:

GM_xmlhttpRequest({
  method: 'GET',
  url: 'https://example.com/image.png',
  binary: true,
  onload: function(response) {
    // response.response is raw binary data
    const imageBlob = new Blob([response.response], { type: 'image/png' });
    const imgElement = document.createElement('img');
    imgElement.src = URL.createObjectURL(imageBlob);
    document.body.appendChild(imgElement);
  }
});

If you left binary: false here, the image bytes would be incorrectly decoded as text, resulting in garbage characters instead of usable image data.

内容的提问来源于stack exchange,提问作者frank

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:22:52