2017-02-28 67 views
0

我有一个XHR对象。当send()方法被触发时,我想提供一个没有服务器的响应,任何网络操作。如何修改XHR

var origSend = xhr.send; 
xhr.send = function() {  
     waitForFile(xhr, url).then(responseData=>{ 
      //ı wantto that responseData , send to xhr response 
      //this responseData comes from anywhere(webrtc,fetch,filesystem,localstorage,......) 
     }); // side-effect 
    FileRequests.next({url: url}) 
    //origSend.call(xhr, arguments) //I don't want to call original send method 
} 

//代码,等待响应

xhr.onreadystatechange = function() { 
if (xhr.readyState == 4 && xhr.status==200) { 
    console.log(xhr.responseText); 
} 
} 

回答

0

我解决这个问题。

 Object.defineProperty(xhr, 'readyState', { 
      writable: true, 
      configurable: true 
     }); 
     Object.defineProperty(xhr, 'status', { 
      writable: true, 
      configurable: true 
     }); 
     Object.defineProperty(xhr, 'statusText', { 
      writable: true, 
      configurable: true 
     }); 
     Object.defineProperty(xhr, 'responseText', { 
      writable: true, 
      configurable: true 
     }); 
     Object.defineProperty(xhr, 'responseType', { 
      writable: true, 
      configurable: true 
     }); 
     Object.defineProperty(xhr, 'response', { 
      writable: true, 
      configurable: true 
     }); 
     xhr.readyState = 4; 
     xhr.status = 200; 
     xhr.statusText = "OK"; 
     xhr.responseType = "blob"; 
     xhr.response = data.blob; // whatever you want 
     xhr.onreadystatechange();