How can I spoof my userAgent using a userscript?

Tags: , , , ,



I’m trying to visit a website but its not allowing me to do so because it doesn’t support my browser. I believe it is detecting my browser through userAgent detection. So I wanted to create a userScript that would modify my userAgent so that the website wouldn’t be able to detect my browser. I tried:

// ==UserScript==
// @name         Change UserAgent
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Spoofs the userAgent
// @author       You
// @include      *
// @run-at       document-start
// ==/UserScript==

Object.defineProperty(navigator, 'userAgent', {
  value: "MyCustomUserAgent",
  configurable: false
});

Even though it shows for me that the userAgent is a custom value, I believe the request for the userAgent is being done before I can spoof it. Is there any way in which I can do so without using an extension? Thank you.

Answer

Userscripts are loaded after the initial HTTP/s connections are made and page is about to load.

By that time, the server has already received the user-agent data. Therefore, a userscript can not spoof the server.

Add-ons can intercept & alter initial communication between the browser & server and thus spoof the user-agent.

Websites that use their own servers (e.g. Google, Yahoo, Facebook etc) have access to their server so spoofing them via userscript is less likely (depending on other factors).

Websites that run on commercial servers may not have access to above server data and have to use JavaScript to get the user-agent, therefore there is a possibility to spoof the user-agent.

Similarly, websites that use page JavaScript that is executed later (e.g. on an event when something is clicked) to obtain the user-agent at that time, can be spoofed with a user-script.



Source: stackoverflow