Javascript Get Browser

Getting the browser that you are using using Javascript can be important in some cases. Like when reading or setting an element’s property, browsers like IE and Firefox both have different ways to do them. Take for example creating a hyperlink using Javascript. To create the text of the hyperlink, IE uses its proprietary innerText property while Firefox uses textContent (although the specific browser will just ignore the property that it cannot recognize, I feel it’s nice to use browser detection to fully ignore the property even if no error will be thrown). Using the function below can be pretty useful in doing conditional statements on which property to apply to an element. The function is custom made, you can modify it if you wish since my only concern was having to know if the browser was IE or not.

Related Posts Plugin for WordPress, Blogger...

2 comments

  1. It has been years since I programmed, I wonder if you have the answer. I assume you love to solve problems and have this solution in your head.
    I just looked at your code Get Browser.
    function getBrowser() {
    var sBrowser = navigator.userAgent;
    if (sBrowser.toLowerCase().indexOf(‘msie’) > -1) return ‘ie’;
    else if (sBrowser.toLowerCase().indexOf(‘firefox’) > -1) return ‘firefox’;
    else return ‘mozilla’;
    }

    I have old code that produces two different results depending on whether the browser is MSIE or Firefox.
    Of course more robust code would be desirable that works for all browsers.
    But for now how do I make it return current year for both browsers

    For MSIE this works.
    copyright=new Date(); update=copyright.getYear()+0; document.write(“Copyright © 1999-“+ update + ” (everyone) All Rights Reserved.”);

    For Firefox this works.
    copyright=new Date(); update=copyright.getYear()+1900; document.write(“Copyright © 1999-“+ update + ” (everyone) All Rights Reserved.”);

Leave a Reply

Your email address will not be published. Required fields are marked *