user3155036
user3155036

Reputation: 167

intercept request headers of XMLHttpRequest javascript

I need to log custom request headers sent to server via all XMLHttpRequests. There are plenty of methods to intercept the request and get url parameter but could not find any describing request headers. Is this even possible ?

Any method is welcome javascript, jquery etc..

Edit: I am not permitted to change any scripts making the ajax queries. I need to intercept the queries by adding another static script.

Upvotes: 0

Views: 2738

Answers (2)

Endless
Endless

Reputation: 37925

This is what service worker do best. Intercepts all requests

self.addEventListener('fetch', function(event) {
    console.log('Handling request for', event.request.url);

    // Do whatever you want with request headers
    event.request.headers.forEach(function(header){

    });
});

The only drawback is that it's not wildly supported. And site has to be in https (service workers only works with https and http if its localhost) This is just what the feature looks like

But I can assure you that you can do it easier with jQuery ajaxStart

Upvotes: 2

Joel R Michaliszen
Joel R Michaliszen

Reputation: 4222

I think exists some events that jquery binds on the document, like ajaxComplete(), so i think what you looking for is the ajaxSend(), I hope be useful see the snippet:

$(document).ajaxSend(function(event, xhr, settings) {
     //this will show the url of the request
     console.log("URL", settings.url)
})

On the settings parameter you can get other header properties.

Upvotes: 0

Related Questions