Home

Awesome

XHook

Easily intercept and modify XHR ("AJAX") request and response

<a href="https://twitter.com/intent/tweet?hashtags=xhook%2Cjavascript%2Cxhr&original_referer=http%3A%2F%2Fgithub.com%2F&text=XHook%3A+Easily+intercept+and+modify+XHR+request+and+response&tw_p=tweetbutton&url=https%3A%2F%2Fgithub.com%2Fjpillora%2Fxhook" target="_blank"> <img src="http://jpillora.com/github-twitter-button/img/tweet.png"></img> </a>

With XHook, you could easily implement functionality to:

Features

Browser Support

Support Modern Browser.

Demos

http://jpillora.com/xhook

Usage

:warning: It's important to include XHook first as other libraries may store a reference to XMLHttpRequest before XHook can patch it

Using script link to load xhook and use it, like so:

<script src="//unpkg.com/xhook@latest/dist/xhook.min.js"></script>
<script>
  xhook.after(function (request, response) {
    if (request.url.match(/example\.txt$/))
      response.text = response.text.replace(/[aeiou]/g, "z");
  });
</script>

We can also install xhook via npm.

npm install xhook

Then use ESM syntax to load xhook.

import xhook from "xhook";
//modify 'responseText' of 'example2.txt'
xhook.after(function (request, response) {
  if (request.url.match(/example\.txt$/))
    response.text = response.text.replace(/[aeiou]/g, "z");
});

API

xhook.before(handler(request[, callback])[, index])

Modifying any property of the request object will modify the underlying XHR before it is sent.

To make the handler is asynchronous, just include the optional callback function, which accepts an optional response object.

To provide a fake response, return or callback() a response object.

xhook.after(handler(request, response[, callback]) [, index])

Modifying any property of the response object will modify the underlying XHR before it is received.

To make the handler is asynchronous, just include the optional callback function.

xhook.enable()

Enables XHook (swaps out the native XMLHttpRequest class). XHook is enabled be default.

xhook.disable()

Disables XHook (swaps the native XMLHttpRequest class back in)


request Object

response Object

Overview

<img src="https://docs.google.com/drawings/d/1PTxHDqdW9iNqagDwtaO0ggXZkJp7ILiRDVWAMHInFGQ/pub?w=498&amp;h=235">

The dark red before hook is returning a response object, which will trigger the after hooks, then trigger the appropriate events, so it appears as if response came from the server.

Reference

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

http://www.w3.org/TR/XMLHttpRequest/

http://www.w3.org/TR/XMLHttpRequest2/

Issues

Contributing

See CONTRIBUTING for instructions on how to build and run XHook locally.

License

MIT License Copyright © 2022 Jaime Pillora dev@jpillora.com