使用纯JavaScript监听具有特定内容的POST事件

时间:2015-10-26 14:58:01

标签: javascript ajax angularjs

我有一个场景,AngularJS网站没有加载任何jQuery(除了包含的jQLite),我需要监听具有特定参数的事件。

我无法编辑任何来源,但是开发控制台中的事件显示它是特定网址的POST事件:https://example.com/ajax/leadgen

我需要监听此POST事件何时包含特定参数,例如: leadType = 25 pageID = abcd

我一直在使用addEventListener查看各种选项,但我无法弄清楚如何将其应用于此场景。

1 个答案:

答案 0 :(得分:0)

您需要覆盖XMLHttpRequest对象才能侦听正在进行的调用。

//Reference the original methods
XMLHttpRequest.prototype._send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype._open = XMLHttpRequest.prototype.open;

//override open
XMLHttpRequest.prototype.open = function () {
   this._url = arguments[1];  //set the url we are opening
   this._open.apply(this,arguments);  //call original open event with arguments
};

//override send
XMLHttpRequest.prototype.send = function () {
   //This is where your logic would need to live.
   console.log(this._url, arguments ? arguments[0] : null);  //read the url we set and the arguments passed into send
   this._send.apply(this, arguments); //call original send event with arguments
};

//Test making an Ajax request
var xhr = new XMLHttpRequest();
xhr.open("POST", window.location.href, true);
xhr.send("a=b");
相关问题