如何拦截和修改XHR?

时间:2019-04-22 11:33:41

标签: javascript xmlhttprequest

我阅读了有关此问题的多个答案,但我不明白自己在做什么错。我希望能够拦截和修改请求和响应。我得到的要求。答案不是。

请求的响应是一个json,我只是希望能够在到达应用程序之前修改响应的url

 <script>
   let oldXHROpen = window.XMLHttpRequest.prototype.open;

   window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
       if (url.startsWith("http://example.com")) {
            url = url.replace("http://example.com", "https://site2.com");      
        } else if (url.startsWith("http://") || url.startsWith("https://")) {
            // do nothing with the url
        } else if (url.startsWith("//")) {
           url = "https:" + url;
        } else if (url.startsWith("/")) {
            url = "https://site2.com" + url;    
        } else if (url.startsWith(".")) {
            url = "https://site2.com" + url.replace("./", "/");     
        } else {
            url = "https://site2.com" + url;
        }

        // This should take care of the response but it is not working.
        this.addEventListener('load', function() {
            var original_response, modified_response;

            original_response = this.responseText;
            Object.defineProperty(this, "responseText", {writable: true});

            modified_response = JSON.parse(original_response);
            modified_response.htmlinfo = "woops! All data has gone!";
            this.responseText = JSON.stringify(modified_response);
       });

       return oldXHROpen.apply(this, arguments);
 }
 </script>

0 个答案:

没有答案
相关问题