View Full Version : Help - Using Objects with If/then Statements

09-26-2011, 08:35 AM
Hi, I am trying to detect a users browsers and output a different code based on browser.

I found this code online that uses the object detection method and it works. When I document.write(BrowserDetect.browser) it outputs Chrome, (which is what I am using). The code can be found here: http://www.quirksmode.org/js/detect.html

So I can't understand why the following code does not work? It ouputs the "not" in the else statement.

I believe that BrowserDetect is an object and the .browser at the end is a property of the object.

Can one not make an object a variable? or make an object a string?

oh and BTW there is a bunch of javascript that creates the browserdetect object that can be found on the site above, but I thought it would be too unwieldy to post here. Thanks.

The following script outputs:
Chrome Not Working

<script type="text/javascript">


var browser="BrowserDetect.browser";

document.write(" Working");
document.write(" Not working");

09-26-2011, 08:44 AM
It doesn't work because you are not calling the BrowserDetect object asking for its property browser, instead you are just assigning "BrowserDetect.browser" as a string value to the variable browser. Remove the quotation marks and it should work:
var browser = BrowserDetect.browser;

document.write("<b>Good morning</b>");
(Also be sure to include PPK:s detection code before your own code...)

09-26-2011, 08:48 AM
Ah...right. Thanks it works!

Philip M
09-26-2011, 09:06 AM
To detect Chrome:-

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') >-1;
alert (is_chrome);
All advice is supplied packaged by intellectual weight, and not by volume. Contents may settle slightly in transit.

09-26-2011, 04:39 PM
You are dealing with a rather academical problem. Usually no one needs to detect browsers; the coders need, most of the time, to detect if a browser has implemented a method or another, thus usually they detect the existence of that method, not of the browser's type.

After all, the browser's type is, most of the time, irrelevant. Same as the color of a cat, as long as she catches mice :)