Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active September 6, 2019 16:40
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save domenic/534c1da00ae7d0ed780d3f3d715d4466 to your computer and use it in GitHub Desktop.
Save domenic/534c1da00ae7d0ed780d3f3d715d4466 to your computer and use it in GitHub Desktop.
Rendering engine UA sniffer
// 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;
}
@tomByrer
Copy link

TY!

BTW, is sniffing the new Edge-Chromium match Edge or Chrome? (I don't have Edge beta to test...)

@domenic
Copy link
Author

domenic commented Jul 10, 2019

It'll match Blink, since that's the rendering engine it uses :).

@developit
Copy link

Here's a glitch running this on the server: https://ua.glitch.me

Screen Shot 2019-07-10 at 12 43 47 PM

@domenic
Copy link
Author

domenic commented Jul 10, 2019

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