1

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.

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

2 Comments

If you notice, the code doesn't actually overwrite XMLHttpRequest, because it defines XmlHttpRequest, beginning with Xml. Very confusing, anyway.
Thanks, I adjusted my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.