How to Use JavaScript to Detect Browser

Wouldn’t it be nice if all of our code looked the same and worked the same no matter what browser our users are viewing our projects or web pages on? That’s the dream, right? Unfortunately, cross browser compatibility isn’t something that a site can achieve without adding some extra code.

There a few ways that you can use code to compensate for different browsers. You can us CSS selector browser hacks, which is a good option, especially if any changes you need to accommodate for are mostly cosmetic and can be fixed with CSS. For more dynamic browser selections, JavaScript is actually a valid way to go.

Below, you’ll find a code snippet that you can use to check for Internet Explorer, Chrome, Firefox, Safari, and Opera. The function checks for these browsers, and will execute any code you insert within the if/else if statements for each browser if the code is run on any of the browsers in question. Use the code to dynamically add classes to your HTML based on the browser, to send alerts to the user based on the browser, to trigger events based on the browser.

Continue Reading Below

The code snippet is lightweight and straightforward, so even the most beginner coders should be able to add it to their projects. Play around with it and see if you can’t achieve that elusive cross-browser compatibility!

function BrowserDetection() {

 //Check if browser is IE
 if (navigator.userAgent.search("MSIE") >= 0) {
 // insert conditional IE code here
 }
 //Check if browser is Chrome
 else if (navigator.userAgent.search("Chrome") >= 0) {
 // insert conditional Chrome code here
 }
 //Check if browser is Firefox 
 else if (navigator.userAgent.search("Firefox") >= 0) {
 // insert conditional Firefox Code here
 }
 //Check if browser is Safari
 else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) {
 // insert conditional Safari code here
 }
 //Check if browser is Opera
 else if (navigator.userAgent.search("Opera") >= 0) {
 // insert conditional Opera code here
 }
 }


Leave a Comment

IMPORTANT:

  • If you wish to post code examples, please wrap them in <code> tags.
  • Multi-line code should be wrapped in <pre><code> </code></pre>
  • Use &lt; instead of < and &gt; instead of > in the examples themselves. Otherwise, you could lose part of the comment when it's submitted.