如何理解GM_xmlhttpRequest的binary参数?测试发现不同取值发送数据一致
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
datais a string (like"a1b2"): Greasemonkey/Tampermonkey will always encode the string to bytes using UTF-8 (the standard for HTTP requests) regardless of thebinarysetting. So whether you setbinary: trueorfalse, the raw byte stream sent to the server is exactly the same. - When your
datais aBlob(likenew Blob([1,2,3])): Blobs are already raw binary data. GM_xmlhttpRequest just sends the blob’s bytes directly, so thebinaryflag 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’sContent-Typeheader (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 aUint8ArrayorBlob, 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

