Skip to content

Instantly share code, notes, and snippets.

@wswoodruff
Last active August 12, 2016 20:39
Show Gist options
  • Save wswoodruff/8b58b9a3cae5548f8d34b6fe3d3f06a6 to your computer and use it in GitHub Desktop.
Save wswoodruff/8b58b9a3cae5548f8d34b6fe3d3f06a6 to your computer and use it in GitHub Desktop.
Non- user agent sniffing browser-detection

#1 Goal: AVOID user agent sniffing as much as possible.

See this link for a necessary evil at times 😅 browser detection: Browser Hacks

var browser;

if(!!window.opera || navigator.userAgent.indexOf(' OPR/') > -1) {
  // Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
  browser = "opera";
} else if(typeof window.InstallTrigger !== 'undefined') {
  // Firefox 1.0+
  browser = "firefox";
} else if(!!window.chrome) {
  // Chrome 1+
  browser = "chrome";
} else if(Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0 || navigator.userAgent.indexOf("Safari") > -1) {
  // At least Safari 3+: "[object HTMLElementConstructor]"
  browser = "safari"
} else if(/*@cc_on!@*/false || !!document.documentMode) {
  // At least IE6
  browser = "ie"
} else {
  browser = "unknown"
}

return browser;

// TODO: To make device detection stronger, do some more duck-type checking:
/*
  Possible additions: Check for pixel ratio, ability to create touch events, lack of canvas context support
*/

var isTablet = (screen.width < '1224' && screen.width >= '768') ? true : false;

var isMobile = screen.width < '768' ? true : false;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment