I'm in a Google Chrome extension with permissions for "*://*/*"
and I'm trying to make the switch from XMLHttpRequest to the Fetch API.
The extension stores user-input login data that used to be put directly into the XHR's open() call for HTTP Auth, but under Fetch can no longer be used directly as a parameter. For HTTP Basic Auth, circumventing this limitation is trivial, as you can manually set an Authorization header:
fetch(url, { headers: new Headers({ 'Authorization': 'Basic ' + btoa(login + ':' + pass) }) } });
HTTP Digest Auth however requires more interactivity; you need to read parameters that the server sends you with its 401 response to craft a valid authorization token. I've tried reading the WWW-Authenticate
response header field with this snippet:
fetch(url).then(function(resp) { resp.headers.forEach(function(val, key) { console.log(key + ' -> ' + val); }); }
But all I get is this output:
content-type -> text/html; charset=iso-8859-1
Which by itself is correct, but that's still missing around 6 more fields according to Chrome's Developer Tools. If I use resp.headers.get("WWW-Authenticate")
(or any of the other fields for that matter), i get only null
.
Any chance of getting to those other fields using the Fetch API?
There is a restriction to access response headers when you are using Fetch API over CORS. Due to this restriction, you can access only following standard headers:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
When you are writing code for Google Chrome extension, you are using CORS, hence you can't access all headers. If you control the server, you can return custom information in the response body
instead of headers
More info on this restriction - https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types
Fetch does not show headers while debugging or if you console.log
response.
You have to use following way to access headers.
response.headers.get('x-auth-token')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With