# Intercept a HTTP request or response

```javascript
document.addEventListener("DOMContentLoaded", function () {
  var originalOpen = XMLHttpRequest.prototype.open;
  var originalSend = XMLHttpRequest.prototype.send;

  XMLHttpRequest.prototype.open = function (method, url) {
    console.log("Intercepted HTTP request: " + method + " " + url);
    originalOpen.apply(this, arguments);
  };

  XMLHttpRequest.prototype.send = function () {
    var self = this;

    // Hooking the onreadystatechange event to intercept the response
    this.onreadystatechange = function () {
      if (self.readyState === 4) {
        console.log(
          "Intercepted HTTP response:",
          JSON.parse(self.responseText),
        );
      }
    };

    originalSend.apply(this, arguments);
  };

  // Example: Making a sample XMLHttpRequest
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "https://jsonplaceholder.typicode.com/todos/1", true);
  xhr.send();
});

//Output
("Intercepted HTTP request: GET https://jsonplaceholder.typicode.com/todos/1");
"Intercepted HTTP response:",
  {
    completed: false,
    id: 1,
    title: "delectus aut autem",
    userId: 1,
  };
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gautamnaik1994.gitbook.io/snippets/web-dev/intercept-a-http-request-or-response.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
