Skip to content

Instantly share code, notes, and snippets.

@rowan-m
Last active June 8, 2022 20:30
Show Gist options
  • Save rowan-m/6f008cb407a81b9d52c00adbb9692929 to your computer and use it in GitHub Desktop.
Save rowan-m/6f008cb407a81b9d52c00adbb9692929 to your computer and use it in GitHub Desktop.
This code might reduce Chrome user-agents
// Only match Chrome user-agents we know we can reduce
// https://www.chromium.org/updates/ua-reduction#TOC-Reduced-User-Agent-String-Reference
const chromeUAs = /^Mozilla\/5\.0 \(((?<platform>Lin|Win|Mac|X11; C|X11; L)+[^\)]+)\) AppleWebKit\/537.36 \(KHTML, like Gecko\) Chrome\/(?<major>\d+)[\d\.]+(?<mobile>[ Mobile]*) Safari\/537\.36$/;
const matched = chromeUAs.exec(navigator.userAgent);
if (matched) {
// Map detected platform to reduced value
const unifiedPlatform = {
'Lin': 'Linux; Android 10; K',
'Win': 'Windows NT 10.0; Win64; x64',
'Mac': 'Macintosh; Intel Mac OS X 10_15_7',
'X11; C': 'X11; CrOS x86_64',
'X11; L': 'X11; Linux x86_64',
};
// Override navigator.userAgent with the reduced string
Object.defineProperty(navigator, 'userAgent', {
value: `Mozilla/5.0 (${unifiedPlatform[matched.groups.platform]}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${matched.groups.major}.0.0.0${matched.groups.mobile} Safari/537.36`,
writable: false,
configurable: true
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment