Accessing the web page's HTTP Headers in JavaScript

前端 未结 17 2622
日久生厌
日久生厌 2020-11-21 04:53

How do I access a page\'s HTTP response headers via JavaScript?

Related to this question, which was modified to ask about accessing two specific HTTP headers.

<
17条回答
  •  离开以前
    2020-11-21 05:38

    A solution with Service Workers

    Service workers are able to access network information, which includes headers. The good part is that it works on any kind of request, not just XMLHttpRequest.

    How it works:

    1. Add a service worker on your website.
    2. Watch every request that's being sent.
    3. Make the service worker fetch the request with the respondWith function.
    4. When the response arrives, read the headers.
    5. Send the headers from the service worker to the page with the postMessage function.

    Working example:

    Service workers are a bit complicated to understand, so I've built a small library that does all this. It is available on github: https://github.com/gmetais/sw-get-headers.

    Limitations:

    • the website needs to be on HTTPS
    • the browser needs to support the Service Workers API
    • the same-domain/cross-domain policies are in action, just like on XMLHttpRequest

提交回复
热议问题