2013-05-03 47 views
3

是否可以將「ArrayBuffer」轉換爲JSON等「可讀」格式?是否有可能將「ArrayBuffer」轉換爲JSON等「可讀」格式? - Chrome擴展

測試腳本:在背景

<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 & param2 = 62或JSON。 謝謝

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

+0

的可能重複[Chrome擴展:如何從內容腳本而不會失去它的類型背景通過ArrayBuffer或斑點?( http://stackoverflow.com/questions/8593896/chrome-extension-how-to-pass-arraybuffer-or-blob-from-content-script-to-the-bac) – 2013-05-03 19:25:10

+0

有沒有解決這個問題? – K2xL 2014-01-18 16:57:40

回答

0

我使用LIB - 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"]); 
相關問題