Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@tomByrer tomByrer commented Jul 10, 2019

TY!

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

@domenic

This comment has been minimized.

Copy link
Owner Author

@domenic domenic commented Jul 10, 2019

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

@developit

This comment has been minimized.

Copy link

@developit developit commented Jul 10, 2019

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

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

@domenic

This comment has been minimized.

Copy link
Owner Author

@domenic 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