Last active
September 6, 2019 16:40
-
-
Save domenic/534c1da00ae7d0ed780d3f3d715d4466 to your computer and use it in GitHub Desktop.
Rendering engine UA sniffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is a minimal UA sniffer, that only cares about the rendering/JS engine | |
// name and version, which should be enough to do feature discrimination and | |
// differential code loading. | |
// | |
// This is distinct from things like https://www.npmjs.com/package/ua-parser-js | |
// which distinguish between different branded browsers that use the same rendering | |
// engine. That sort of distinction is maybe useful for analytics purposes, but | |
// for differential code loading it is overcomplicated. | |
// | |
// This is meant to demonstrate that UA sniffing is not really that hard if you're | |
// trying to accomplish things like https://github.com/whatwg/html/issues/4432. | |
function getRenderingEngine() { | |
// Order is important because of how browsers pretend to be each other | |
const edge = /Edge\/([^ ]+)/.exec(navigator.userAgent); | |
if (edge) { | |
return { engine: "EdgeHTML", version: edge[1] }; | |
} | |
// Will also catch anything using Blink (e.g. Samsung Browser) | |
const chrome = /Chrome\/([^ ]+)/.exec(navigator.userAgent); | |
if (chrome) { | |
return { engine: "Blink", version: chrome[1] }; | |
} | |
// Will also catch anything using WebKit (e.g. Chrome iOS) | |
// Note: cannot inspect AppleWebKit/X number as it is frozen. | |
// https://bugs.webkit.org/show_bug.cgi?id=182629 | |
const safari = /AppleWebKit\/(?:[^ ]+) \(KHTML, like Gecko\) Version\/([^ ]+)/.exec(navigator.userAgent); | |
if (safari) { | |
return { engine: "WebKit", version: safari[1] }; | |
} | |
// Will also catch anything using Gecko (e.g. Iceweasel) | |
const firefox = /Firefox\/([^ ]+)/.exec(navigator.userAgent); | |
if (firefox) { | |
return { engine: "Gecko", version: firefox[1] }; | |
} | |
// Assume too old; serve the lowest-level code you support. | |
// Could be Presto (old Opera), Trident (IE), Lynx, ... | |
return null; | |
} |
Here's a glitch running this on the server: https://ua.glitch.me
Sweet. Next demo: use private fields in Chrome 74+, transpile to underscore-prefixed in other browsers.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It'll match Blink, since that's the rendering engine it uses :).