Obtain the method and url from an XHR - javascript

Basically what the title says, I want to get the URL and HTTP Verb from a xhr. Is this possible?

Not natively, I'm afraid. In prototypable implementations you could write your own prototype:
XMLHttpRequest.prototype.__oldOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.verb = "";
XMLHttpRequest.prototype.url = "";
XMLHttpRequest.prototype.open = function (verb, url, async)
{
this.verb = verb;
this.url = url;
this.__oldOpen.call(this, verb, url, async);
}
Don't expect it to work in IE7 and older though.
I suppose you could do it by completely recreating the XMLHttpRequest object, but it would take a lot of work to get it right:
var oldXHR = XMLHttpRequest;
function XMLHttpRequest()
{
var realXHR = new oldXHR();
this.onreadystatechange = function () {}
this.open = function (verb, url, async)
{
this.verb = verb;
this.url = url;
realXHR.open(verb, url, async);
{
this.send = function () { realXHR.send(); }
// all other properties and methods...
}
Of course, you have to go to the effort of correctly binding onreadystatechange and setting the status, etc.

Currently, there is no standard way to get HTTP verb or url from XHR object. But, W3C is considering getRequestHeader for future considerations.

Related

Variable in JavaScript, why putting `var` does not work?

When I put var in front of method and url (var method, and var url) the code does not work.
function intervalcheck(theObject) {
var xmlhttp = new XMLHttpRequest(),
method = 'POST',
url = 'https://thekmui.com/payb/payresult/result.php';
xmlhttp.open(method, url, true);
xmlhttp.onload = function () {
Take a look at here:
var xmlhttp = new XMLHttpRequest(),
method = 'POST',
You are putting ','(comma) after each line. Either you leave it empty and browser handle the rest. Or you can put ';' semi-colon like this:
var xmlhttp = new XMLHttpRequest();
method = 'POST';
Otherwise the code will produce a massive error.
You may follow this post as well:
Send POST data using XMLHttpRequest

RequireJS / XMLHttpRequest issue - TypeError: Cannot find function open in object function localRequire(deps, callback, errback) {...}

I've been trying to get info from JIRA REST API to put it in cells inside a spreadsheet. For this I'm writing a Google script attached to the spreadsheet, so, form what I understand, that makes this "in Browser" stuff.
In my project I currently have a main code script as well as the requirejs script (I read that it would be the way for me to call xmlhttprequest from a browser script).
Please keep in mind I'm not that used to scripting and mostly tried to follow documentations, but I must be missing something because I always get this error:
TypeError: Cannot find function open in object function localRequire(deps, callback, errback) {...}.
Here's my function so far:
function updateFilters()
{
var Test = destinationSpreadsheet.setActiveSheet(destinationSpreadsheet.getSheetByName("Nonsense"));
var url = "myurl is in there"; //I have a test url in there
var XMLHttpRequest = require(["xmlhttprequest"], function(xmlhttprequest){});
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url);
myRequest.onload = function ()
{
console.Log(myRequest.response);
};
}
I'm confused as to why "open" doesn't work. There seem to be no issue when I comment out the line, but of course if I do that I get nothing.
Try this for javascript:
function updateFilters()
{
var url = "myurl is in there"; //I have a test url in there
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url);
myRequest.onload = function ()
{
console.Log(myRequest.response);
};
}
This line is breaking your code:
var XMLHttpRequest = require(["xmlhttprequest"], function(xmlhttprequest){});
Try this for node.js:
function updateFilters()
{
var url = "myurl is in there"; //I have a test url in there
const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url);
myRequest.onload = function ()
{
console.Log(myRequest.response);
};
}
Note: you new to install xmlhttprequest with npm or yarn first

intercepting XHR requests, javascript react

I have been trying to override the methods in order to intercept the xhr requests but seems like everything I do it only prinds '1' for this.readyState.
Does anyone have any idea why?
addInterceptorsToXHRRequests() {
const originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
const originalStateChangeHandler = this.onreadystatechange;
this.onreadystatechange = function() {
console.log(' ---> ',this.readyState);
if (originalStateChangeHandler instanceof Function) {
originalStateChangeHandler.apply(this, arguments);
console.log('Ready state: ' + this.readyState);
}
};
return originalOpen.apply(this, arguments);
};
}
I am calling this function from index.js, at the end of componentDidMount life cycle method. (pretty big project)
This happens because you bind a function on XMLHttpRequest.prototype.open .
open returns only state 1.
So, you need to attach the onreadystatechange function to the full xhr.
Example
// you probably want the original XMLHttpRequest here...
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
console.log(xhr.readyState);
};

HTTP post in iMacros with Javascript for Firefox

I was making a automation script to extract some info from a website, And It's important to submit some info using POST method. Can anyone tell me how to use HTTP Post method with Imacro & javascript for firefox plugin. Below is the script which i found here : Sending an HTTP Post using Javascript triggered event
But it's giving me error when i play the same using Imacro player.
var url = "http://www.google.com/";
var method = "POST";
var postData = "Some data";
var async = true;
var request = new XMLHttpRequest();
request.onload = function () {
var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
var data = request.responseText; // Returned data, e.g., an HTML document.
}
request.open(method, url, async);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.send(postData);
XMLHttpRequest() is no longer supported in firefox 15+
You have to define it:
const XMLHttpRequest = Components.Constructor("#mozilla.org/xmlextras/xmlhttprequest;1");
var request = XMLHttpRequest();
To run JavaScript in iMacros you can use this method.
URL GOTO=javascript:window.ScrollTo(0,150);
Try this method.
In your case it would look like this.
URL GOTO=javascript:var url = "http://www.google.com/";var method = "POST";var postData = "Some data";var async = true;var request = new XMLHttpRequest();request.onload = function () var status = request.status; var data = request.responseText; request.open(method, url, async);request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");request.send(postData);

Hook into XMLHttpRequest open and send method

I am using the following code to hook into XMLHttpRequest open/send methods:
var lastParams = '';
var send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(data){
lastParams = data;
send.call(this, data);
};
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) {
this.addEventListener("readystatechange", function(event) {
if(this.readyState == 4){
var self = this;
var response = {
method: method,
uri: uri,
params: lastParams,
responseText: self.responseText
};
console.log(response);
}
}, false);
open.call(this, method, uri, async, user, pass);
};
It is working fine in the case of single ajax request at a time.
When multiple ajax request are firing at a time, then lastParams can contain wrong data (means lastParams can contain data from other ajax request). I want to uniquely associate the lastParams with request's other attributes?
Is there any id attribute in XMLHttpRequest so that I can uniquely identify the ajax request instance?
Thanks in advance.
Have a look at https://github.com/jpillora/xhook and the demos
//modify 'responseText' of 'example2.txt'
xhook.after(function(request, response) {
if(request.url.match(/example\.txt$/)) {
response.text = response.text.replace(/[aeiou]/g,'z');
}
});
For uniquely associating some data with specified XMLHttpRequest instance you can simply add property into XMLHttpRequest instance and save data into property. For example:
// generating data for request
var data=generateData();
// sending data
var xhr=new XMLHttpRequest();
xhr.open("POST","/yourpage.php",true);
xhr.onreadystatechange=function(event){
if(this.readyState===4){
console.log(this.mySendedData);
}
};
/** if you need to preserve 'data' variable value for each xhr **/
xhr.mySendedData=data;
/***************************************************************/
xhr.send(data);
why not make 'lastParams' as an array, and you always push data, instead of overwriting it everytime.

Categories