Skip to content

Instantly share code, notes, and snippets.

@r17x
Last active June 29, 2018 00:21
Show Gist options
  • Save r17x/b296a88d5e4f58eebe6321bf5a5f0134 to your computer and use it in GitHub Desktop.
Save r17x/b296a88d5e4f58eebe6321bf5a5f0134 to your computer and use it in GitHub Desktop.
Overwrite & Replace Original Window.fetch for something logic & get information in every request & response

This code for get all information on event in request/response (XHR/Fetch) you can manipulation everything in Request/Response like headers, data, & etc.

i don't want to handle 10++ request for get something in request/response, so overwrite window.fetch (globally) to do it.

const OriginalFetch = window.fetch

window.fetch = (url, options) => {
  const promise = OriginalFetch(url, options)
  promise.then((response) => {
    /** 
     * What you want here
     * this just example to get Headers like x-csrf-token
     * on response.
     */
    const csrf = response.headers.get('x-csrf-token')
    if (csrf) {
    /* 
     * Last Response always set sessionStorage for
     * csrf_token value
     * sessionStorage its optional
     * you can use another in WebStorage
     */
    window.sessionStorage.setItem('csrf_token', csrf)
    }
  })
  return promise
}

/* get X-CSRF-Token in SessionStorage after Request end. */
window.sessionStorage.getItem('csrf_token')

Happy Hacking

  • @ri7nz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment