Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Ajax Request: Change User-Agent

I'm using JQuery to issue an AJAX request to my own Webservice. I need to set or modify the User-Agent HTTP-Header for the HTTP-AJAX-Request, how can I do this the easiest way?

I tried the hint provided by some users to use the setRequestHeader Method to set the User-Agent, but this does not work. It does in fact work for other newly created headers (like X-Test-Header) but it does not work for User-Agent.

like image 511
theomega Avatar asked Apr 24 '11 16:04

theomega


4 Answers

It is simply impossible, you are not allowed to change the user-agent for XMLHttpRequests. I'm not sure if this is valid for Internet-Explorer, but the w3c specifies here:

The setRequestHeader() method

[...]

When the setRequestHeader(header, value) method is invoked, the user agent must run these steps: [...]

Terminate these steps if header is a case-insensitive match for one of the following headers:

[...]

  • User-Agent
like image 126
theomega Avatar answered Oct 28 '22 09:10

theomega


If you are using jQuery, set the request header in the ajaxSetup.

$.ajaxSetup({
  beforeSend: function(request) {
    request.setRequestHeader("User-Agent","InsertUserAgentStringHere");
  }
});
like image 21
Peter Olson Avatar answered Oct 28 '22 08:10

Peter Olson


Well, you could always use jQuery to post to a server-side page which then in turn is able to modify the User-Agent header, and also make a request to the page which would have been directly accessed by jQuery.

like image 6
Lucas Avatar answered Oct 28 '22 09:10

Lucas


A way to do this is to overwrite the native code in the __defineGetter__ method of the window.navigator object.

Check this out:

window.navigator.__defineGetter__('userAgent', function () {
    return "___I'M A GHOST___";
});

Run navigator.userAgent in the console before and after to check.

Works in Chrome. I haven't checked other browsers.

You can read more about it here: https://www.codeproject.com/Tips/1036762/Mocking-userAgent-with-JavaScript

like image 2
riot Avatar answered Oct 28 '22 09:10

riot