English 中文(简体)
Intercept XMLHttpRequest and Russia responseText
原标题:Intercept XMLHttpRequest and modify responseText

我试图打造一个文字,作为本地人的替代/交换器,XMLHttpRequest,使我能够拦截该文本,修改复方复原地改变活动。

如果当地储存已经提供数据,则该数据试图接收,便可浏览XMLHttpRequest,并将当地储存的数据反馈到数据的成功/反馈方法中。 Assume I对AJAX现有备用方法没有控制。

I had originally tried the following idea..

var send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data){
   //Do some stuff in here to modify the responseText
   send.call(this, data);
};

但是,正如我现在已经确定的那样,复文仅读。

然后,我尝试退一步,写上我自己的全本土代理人,以XMLHttpRequest,最终完成我自己版本的本土方法。 类似于这里讨论的内容......

http://www.ilinsky.com/articles/XMLHttpRequest/#implementation-wrapping

但是,它迅速混淆,仍然难以将修改后的数据退回到原来的方法中。

任何建议? 这样做是否可行?

最佳回答

//
// firefox, ie8+ 
//
var accessor = Object.getOwnPropertyDescriptor(XMLHttpRequest.prototype,  responseText );

Object.defineProperty(XMLHttpRequest.prototype,  responseText , {
	get: function() {
		console.log( get responseText );
		return accessor.get.call(this);
	},
	set: function(str) {
		console.log( set responseText: %s , str);
		//return accessor.set.call(this, str);
	},
	configurable: true
});


//
// chrome, safari (accessor == null)
//
var rawOpen = XMLHttpRequest.prototype.open;

XMLHttpRequest.prototype.open = function() {
	if (!this._hooked) {
		this._hooked = true;
		setupHook(this);
	}
	rawOpen.apply(this, arguments);
}

function setupHook(xhr) {
	function getter() {
		console.log( get responseText );

		delete xhr.responseText;
		var ret = xhr.responseText;
		setup();
		return ret;
	}

	function setter(str) {
		console.log( set responseText: %s , str);
	}

	function setup() {
		Object.defineProperty(xhr,  responseText , {
			get: getter,
			set: setter,
			configurable: true
		});
	}
	setup();
}
问题回答

The following script perfectly intercept the data before sending via XMLHttpRequest.prototype.send

<script>
(function(send) { 

        XMLHttpRequest.prototype.send = function(data) { 

            this.addEventListener( readystatechange , function() { 

            }, false); 

            console.log(data); 
            alert(data); 

        }; 

})(XMLHttpRequest.prototype.send);
</script>

我认为,为了拦截<条码>XMLHttpRequest的回复,将采用一种更现代的解决办法,将原XMLHttpRequest和在<条码>>>>上将其搁置。 反对:

const { interceptXhrResponse } = (function () {
  let interceptionRules = [];

  /**
   * Function to intercept responses for given URL patterns
   * @param {RegExp} urlPattern - Regular expression to match the (canonicalized) URL
   * @param {Function} responseHandler - Function to handle the intercepted response
   */
  function interceptXhrResponse(urlPattern, responseHandler) {
    interceptionRules.push({ urlPattern, responseHandler });
  }

  // Function to find specific handler for the URL and return modified response
  function handleInterceptedResponse(response, url) {
    const interceptionRule = interceptionRules.find(({ urlPattern }) =>
      urlPattern.test(url)
    );

    if (interceptionRule) {
      const { responseHandler } = interceptionRule;
      return responseHandler(response, url);
    }

    return response;
  }

  const OriginalXMLHttpRequest = window.XMLHttpRequest;

  class XMLHttpRequest extends OriginalXMLHttpRequest {
    get responseText() {
      // If the request is not done, return the original responseText
      if (this.readyState !== 4) {
        return super.responseText;
      }

      return handleInterceptedResponse(super.responseText, this.responseURL);
    }

    get response() {
      // If the request is not done, return the original response
      if (this.readyState !== 4) {
        return super.response;
      }

      return handleInterceptedResponse(super.response, this.responseURL);
    }
  }

  window.XMLHttpRequest = XMLHttpRequest;

  return { interceptXhrResponse };
})();

上限代码显示<代码>interceptXhrResponse<>code>功能,使您能够以定期表述和相应的回复手写明URL型号。 你可以把你想要的手里的东西回去,改变对策。

例如:

interceptXhrResponse(/.+/, (response, url) => {
  return `Response of ${url}: Intercepted. Original response length: ${String(response).length}`
})

然后,我们可以尝试启动XMLHttpRequest:

const xhr = new XMLHttpRequest()
xhr.open( GET ,  https://stackoverflow.com/404 )
xhr.send()
xhr.onloadend = () => {
  console.log(xhr.responseText)
}

产出:

Response of https://stackoverflow.com/404: Intercepted. Original response length: 63486

被接受的回答是,直到最近,由于某种原因,我才在Twitter上工作。 这里是另一个行之有效的:

        var open_prototype = XMLHttpRequest.prototype.open
        unsafeWindow.XMLHttpRequest.prototype.open = function() {
            this.addEventListener( readystatechange , function(event) {
                if ( this.readyState === 4 ) {
                    var response = event.target.responseText.replaceAll("a", "b");
                    Object.defineProperty(this,  response , {writable: true});
                    Object.defineProperty(this,  responseText , {writable: true});
                    this.response = this.responseText = response;
                }
            });
            return open_prototype.apply(this, arguments);
        };

页: 1





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签