Is it possible to create a Javascript and include it in a web page that the function of this JS is to "catch" all GET request or any other Ajax calls made from any other Javascript on the page? Either to log it or just plain show it in a Alert box.
The "other Javacript" that will be executing GET or Ajax calls is arbitrary. I mean I have no control over that in terms of what it is.
And once caught I need to check which Javascript executing which GET or Ajax calls.
Is this possible?
Try this snippet. It extends the send function so that you can execute something before or after the real sending.
XMLHttpRequest.prototype.reallySend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function(body) {
// Do something...
this.reallySend(body);
};
var req = new XMLHttpRequest();
req.open("GET", "any.html", true);
req.send(null);
const nativeOpen = XMLHttpRequest.prototype.open;
const proxiedOpen = function () {
if (arguments[1].includes('youUrl.com')) {
// do some ...
}
nativeOpen.apply(this, arguments);
};
Refer to the answer:
Intercept AND CHANGE the results of an ajax call
Related
I'm new to Javascript and am trying to write a userscript which tracks all Ajax calls made within a specific website and if the reponse status code is not 200, I want to automatically repeat that request.
Also these requests I want to repeat are all POST requests which probably makes it even harder.
I've come so far that I'm tracking all Ajax calls but since it seems to be impossible to capture the formdata sent from the POST requests, I don't know how I could repeat the failed calls.
(function() { // Overriding XMLHttpRequest
var oldXHR = window.XMLHttpRequest;
function newXHR() {
var realXHR = new oldXHR();
realXHR.addEventListener("readystatechange", function() {
console.log("an ajax request was made")
console.log(realXHR.status)
//If the status is not 200, repeat the request with same data etc
}, false);
return realXHR;
}
window.XMLHttpRequest = newXHR;
})();
You can try by calling the same function again
if(realXHR.status !==200){
newXHR();
}
I am trying to make api call to get spotify albums in native javascript without using any js frameworks. I am running into issues where I am unable to send Oauth token using native js. For spotify I have client id and client scret. I can either use that or the Oa
(function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.spotify.com/v1/albums", false);
xhr.send();
document.getElementById("results").innerHTML = xhr.responseText;
})();
function request(callback) {
var xobj = new XMLHttpRequest();
// true parameter denotes asynchronous
xobj.open('GET', YOUR_URL_HERE, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// This marks that the response has been successfully retrieved from the server
// Utilize callback
callback(xobj.responseText);
}
};
xobj.send(null);
}
I would definitely recommend taking a look at the link Frobber provided. It's always better to understand why something does/doesn't work rather than just getting it to work. Here is a mock request to get you started. Hope this helps!
I think you need to read a basic tutorial on how to use XMLHttpRequest, which you can find here
One immediate problem with your code is that it's not using any callback to read the result that comes back from the server. This is all happening asynchronously, so what's occurring in your case is that you're send()ing the request, and then immediately setting innerHTML to a value that probably isn't even available from the server yet.
Check the tutorial for how to get that information back from the server when it's ready.
Note the use of the myFunction callback, and note the use of onreadystatechange. What's happening here is that send() is sending something to the server, in a separate execution thread. You need to register a callback function that will perform the data fetching and DOM update when the server reports back that the data is available, not immediately.
In my web application, what the user does on the page have to be sent my database, so I have the latest changes saved.
I just call the function with the request here when the user close the page:
window.onbeforeunload = sendData;
But where the problems come up is when I send data every 10 second. I do send my requests sync and not async (or it would not be sent onbeforeunload). The problem is that this adds delays to the user interface when the data is sent every 10 second.
setInterval(sendData,10000);
This is what's getting called:
function sendData(){
var xhr = new XMLHttpRequest();
var localData = datatodatabase;
xhr.open("POST", "handler.php", false);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("pack="+datatodatabase);
}
Is it possible to add this inside a Web Worker to make the synchronized requests stop delaying what everything else is going on?
(As I said: I have to use synchronized because of onbeforeunload)
Why don't you make it asynchronous every 10 seconds, but onbeforeunload make it synchronous? Like this:
setInterval(function () {
sendData(true);
}, 10000);
window.onbeforeunload = function () {
sendData(false);
}
function sendData(async) {
// Make the ajax call the specific way based on whether *async* is *true* or *false*
// Probably eventually:
xhr.open("POST", "handler.php", async);
}
I'm new in JS, and having quite hard time reading the following JS code.
The first parameter of the function is a url to a PHP script, the second is a string.
What confuses me is how to read code after the line:
self.xmlHttpReq.open('POST', strURL, true);
What happens after this? Which code should i look after this line? The script?
What happens after open?
function check_detail(strURL, pids)
{
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function()
{
if (self.xmlHttpReq.readyState == 4)
updatepage(self.xmlHttpReq.responseText, pids);
}
self.xmlHttpReq.send(getquery(pids));
}
The key is the call to "send()", which actually launches the HTTP request. That happens, but the code then proceeds immediately without waiting for the result.
When the server responds, the browser will invoke the anonymous function set up as the "readystatechange" handler. Exactly when that happens is unpredictable; it's asynchronous, in other words.
Thus, the "updatepage()" call will happen long after the "check_detail()" function has returned.
When you make an Ajax request (which is what you are doing here) it is asynchronous, which means that you don't know exactly when it will return so you can't just wait for the return.
Instead, you set up your function so that, when the request returns, a function is kicked off to handle the response. This is the onreadystatechange piece.
So the chronology will be: first the send() will occur, which will send the result of the getquery() method up to the PHP page. When that returns, the function defined within onreadystatechange will fire, which will call updatepage() and pass it both the text that was sent back from the Ajax call, and also the pids parameter.
If you're new to JavaScript, then I'd say it's a waste of time trying to figure out what's going on here - you're learning how to use the XHR object, how to make that cross-browser, and you're learning JavaScript at the same time.
I'd recommend doing the Ajax with a JavaScript library such as jQuery - don't try to learn it all now while you're learning JavaScript as well.
Most of that could be replaced with something along the lines of:
$.post(strURL, function (data) {
updatePage(data);
});
this is simple Ajax function
function check_detail(strURL, pids)
{
// definning new variable
var xmlHttpReq = false;
// creating variable self which will function as this
var self = this;
// creating HTTP request maker for Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// creating HTTP request maker in IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
// so this is the confusing part right ?
// xmlHttpReq.open opens connection tu the strURL and infomation sending method
// will be POST method ( other passible values can be GET method or even else )
self.xmlHttpReq.open('POST', strURL, true);
// this defines HTTP request header (small information about what we are sending)
// in fact this is sending Content-type of information
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// when HTTP request maker state will be changed for example:
// the data will be sent or data will be received this function will be fired
self.xmlHttpReq.onreadystatechange = function()
{
// readyState 4 means data has been received
if (self.xmlHttpReq.readyState == 4)
updatepage(self.xmlHttpReq.responseText, pids); // updatepage is user defined function
}
// this actually sends the HTTP request which is made above
// but don't be confused because of this code ordering
// I mean the function defining what to do when content will be received is implemented
// before sending HTTP request right ?
// thats because if the data is too small and internet is really fast HTTP query can be
// executed faster then defining new function which will cause javascript error
self.xmlHttpReq.send(getquery(pids));
}
hope this helps
if not
more about ajax: http://en.wikipedia.org/wiki/Ajax_(programming)
I have session key that is a JavaScript variable which I got from a REST API call. I need to call my Java code in a servlet and pass that key as a parameter. What JavaScript function can I use to do that?
Several ways:
Use window.location to fire a GET request. Caveat is that it"s synchronous (so the client will see the current page being changed).
window.location = "http://example.com/servlet?key=" + encodeURIComponent(key);
Note the importance of built-in encodeURIComponent() function to encode the request parameters before passing it.
Use form.submit() to fire a GET or POST request. The caveat is also that it"s synchronous.
document.formname.key.value = key;
document.formname.submit();
With
<form name="formname" action="servlet" method="post">
<input type="hidden" name="key">
</form>
Alternatively you can also only set the hidden field of an existing form and just wait until the user submits it.
Use XMLHttpRequest#send() to fire an asynchronous request in the background (also known as Ajax). Below example will invoke servlet"s doGet().
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://example.com/servlet?key=" + encodeURIComponent(key));
xhr.send(null);
Below example will invoke servlet"s doPost().
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://example.com/servlet");
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("key=" + encodeURIComponent(key));
Use jQuery to send a crossbrowser compatible Ajax request (above xhr code works in real browsers only, for MSIE compatibility, you"ll need to add some clutter ;) ).
$.get("http://example.com/servlet", { "key": key });
$.post("http://example.com/servlet", { "key": key });
Note that jQuery already transparently encodes the request parameters all by itself, so you don"t need encodeURIComponent() here.
Either way, the key will be just available by request.getParameter("key") in the servlet.
See also:
How to use Servlets and Ajax?
Access Java / Servlet / JSP / JSTL / EL variables in JavaScript
No JavaScript function per se, but browsers usually* provide an XMLHttpRequest object and you can go through that.
Libraries such as YUI and jQuery provide helper functions to simplify its usage.
* for a value of "usually" that includes pretty much any browser that supports JavaScript and was released since Netscape 4 died
When sending POST add header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
The code looks like
Client:
function executeRequest(req) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("response").value = xhttp.responseText;
}
};
xhttp.open("POST", "execute/cardbrowser", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("lorem=ipsum&name=binny");
}
Server:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println(req.getParameter("lorem"));
}