Lasantha Bandara
Lasantha Bandara

Reputation: 809

How to detect an HTTP request of a browser using Javascript?

I'm developing an ASP.NET MVC 3 Web Application. I need to catch any web request going from my web interface and add some values into its header. So I'm searching how to detect the http request going from web browser, using Javascript. I don't know whether it is possible.

I tried with this Ajax request and it works.

    function loadXMLDoc() {

        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            window.XmlHttpRequest = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            window.XmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }

          window.XmlHttpRequest.onreadystatechange = function () {
          alert(window.XmlHttpRequest.readyState + "  " + window.XmlHttpRequest.status);

          if (window.XmlHttpRequest.readyState == 4 && window.XmlHttpRequest.status == 200) {
             document.getElementById("myDiv").innerHTML = window.XmlHttpRequest.responseText;
          }
        };

        window.XmlHttpRequest.open("GET", "@Url.Action("TestActionForJScripts","User")", true);
        window.XmlHttpRequest.setRequestHeader("TestKey", "TestValue");
        window.XmlHttpRequest.send();
    }

But I do not need to create a request object. I'm trying to catch requests generating from buttons, links, etc.

Upvotes: 1

Views: 4139

Answers (1)

Bergi
Bergi

Reputation: 664620

window.XmlHttpRequest = new XMLHttpRequest();

XmlHttpRequest looks like a constructor function because of its capital name. You should

  • rename it to lowercase which is less confusing, or at least use something like MyXhrInstance...
  • make it a local variable of that function instead of a global property of the window object

catch any web request going from my web interface

You should use a library function, or at least use something common as your function loadXMLDoc() everywhere. There is no need to do this everywhere, follow the DRY principle. Use arguments for that function to make it adaptable, instead of using a fixed url for example.

...and add some values into its header

Do this just in the common used function.

Upvotes: 3

Related Questions