Click here to Skip to main content
14,334,249 members

Mocking userAgent with JavaScript

Rate this:
5.00 (4 votes)
Please Sign up or sign in to vote.
5.00 (4 votes)
9 Oct 2015CPOL
This tip briefly shows how to change your user agent or any other data in window.navigator object.


Navigator is a JavaScipt object which provides information about your browser.

Many sites/technologies logic are based on that data for specific implementations. For instance, not all browsers support the same JavaScript features, so that's one of the ways for companies to deal with that issue in order to create a cross browser JavaScript code.

Navigator should provide reliable information, still sometimes, you'll need to change its data for your benefit.

How I Got Here (Can Be Skipped)

I've encountered this problem as I was developing Cordova app as Windows Universal App for Windows Phone.

Phone browser (Internet Explorer) set my appVersion with 'Windows Phone 8.1' as my userAgent, then cordova.js loaded the phones WinJS script accordingly ("Microsoft.Phone.WinJS.2.1/js/base.js" instead of "/WinJS/js/base.js"), this phone script was missing some of the Universal App WinJS features that I needed, so I had to change it.

Setting window.navigator.__defineGetter__

As you probably already guessed by the function name, __defineGetter__ function will define getters in our window.navigator object, however if you'll write : window.navigator.__defineGetter__ in your console, you will get:

function __defineGetter__() { [native code] }?

That's because it's a native function.

Setting Getters

__defineGetter__ accepts key as a first argument and a function as second. The key is the name of the property, and the function should return the value of the property you named.

window.navigator.__defineGetter__('appVersion', function () {
	return 'this is your app Version';

Similarly, you can use it for any property you want to change in the navigator object.

Settings Getter for userAgent Value

window.navigator.__defineGetter__('userAgent', function () {
	return '__USER__AGENT_DEMO___';
  • You can set a breakpoint in the function that you've passed as second parameter, and you'll see that you'll hit it as you access the property.

After you set your getters, check it out in your console:

Image 1


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Pavel Durov
Software Developer
Israel Israel
No Biography provided

Comments and Discussions

-- There are no messages in this forum --
Posted 9 Oct 2015


3 bookmarked