Question

I am new to ajax and need some help in understanding how javascript runs in a browser. The problem I am trying to solve is to intercept ajax responses using a second javascript(injected into this page).

When the user first loads the page, I modify the server response(through proxy) by appending my own javascript. Later during normal operation user tries to get some content through this page, I want to be able to intercept this response when it contains specific http headers or content using the injected javascript and show a popup.

Is this even feasible? I checked other related questions and found that this can be done using browser extensions(content scripts etc) but I would like to know if this possible using javascript injection on the page itself.

Was it helpful?

Solution

How do you intend to intercept the AJAX response? The only way I see that's possible using JavaScript is if you have access to the original XMLHttpRequest object. Consider:

var request = new XMLHttpRequest;
request.onreadystatechange = handler;
request.open("GET", "/somefile.php", true);
request.send();

function handler() {
    if (request.readyState == 4 && request.status == 200) {
        // do something
    }
}

Now to intercept this AJAX response you would need to override the request.onreadystatechange event handler and to do so you would need access to the request object.

Since you are trying to intercept the response using an injected script your script will only have access to global variables, which means that you'll only be able to intercept the AJAX response if the request object is a global variable.

Even then you can never be sure that the script which you inject will be executed before, after or during the AJAX request. The best you can do is check the readyState of the request and simply give up if it's too late.

If you're trying to launch an XSS attack intercepting AJAX responses are definitely not viable. Cheers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top