4

是否可以将“ArrayBuffer”转换为 JSON 等“可读”格式?

测试脚本:

<script>
try {
   http = new ActiveXObject("Microsoft.XMLHTTP");   // Trying IE
}
catch(e)    // Failed, use standard object 
{
  http = new XMLHttpRequest(); 
}

var url = "http://localhost/test.htm";
var params = "param=abc&param2=62";
http.open("POST", url, true);

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert('send..');
    }
}
http.send(params);
</script>

在背景上(chrome 扩展)请求监听器:( 从 test.htm 接收 xhr)

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        console.log(details); 
},
{
urls: ["*://localhost/*"]
},
['requestBody']);

console.log 结果:

Object {frameId: 0, method: "POST", parentFrameId: -1, requestBody: Object, requestId: "12981"…}
frameId: 0
method: "POST"
parentFrameId: -1
requestBody: Object
raw: Array[1]
0: Object
bytes: ArrayBuffer
byteLength: 32
__proto__: ArrayBuffer
constructor: function ArrayBuffer() { [native code] }
slice: function slice() { [native code] }
__proto__: Object
__proto__: Object
length: 1
__proto__: Array[0]
__proto__: Object
requestId: "12981"
tabId: 180
timeStamp: 1367604574726.125
type: "xmlhttprequest"
url: "http://localhost/test.htm"
__proto__: Object

我需要将 details.requestBody.raw 转换回 param=abc¶m2=62 或 JSON。谢谢

http://developer.chrome.com/dev/extensions/webRequest.html

4

1 回答 1

2

我使用那个库 - https://github.com/vicetjs/array-buffer-to-data

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        try {
            if (details && details.type === "xmlhttprequest" && 
                var buffer = details.requestBody.raw[0].bytes;
                console.log(arrayBufferToData.toJSON(buffer));//JSON payload body
            }
            return {requestHeaders: details.requestHeaders};
        } catch(e) {
            console.log(e.stack);
        } 
    },
    {urls: ["<all_urls>"]},
    ["requestBody"]);
于 2016-06-02T20:15:44.373 回答