![]() |
|
| |||
The Need For Browser DetectionNetscape and Internet Explorer often refer to JavaScript objects differently. This means that, in many cases, a JavaScript reference/statement that works in one browser will not work in the other. To get around this, we must be able to determine which browser is being used and direct it to the code appropriate for it. Another use for browser detection is in determining if the viewer is using an older browser that might not support an effect we've coded. In this case, the "navigator.appVersion" can be employed to detect the older browser and redirect it to a more appropriate page or post a warning. We've not run across any "cross-browser" issues yet. I wanted you to understand browser detection before you needed it. In this lesson we'll make up a problem -- that Internet Explorer can't display the color green -- and use "navigator.appName" along with the IF/ELSE statement to work around this problem. Of course, IE can display a variety of shades of green, I'm just using this as an example. Detection By appNameTo detect and redirect a browser to appropriate code we'll use the IF/ELSE statement. As with all browser detection, we'll want to put this code at the top of the function or outside all functions right after the opening <script> tag in our <head>. Browser detection must be done before the code in question is run. Otherwise, the wrong code could be run and produce errors. Remember that when browser detection is needed, it must be done first. To detect a browser by name we use the following condition in our IF statement:
if (navigator.appName == "Microsoft Internet Explorer") Notice that the term "Microsoft Internet Explorer" is in quotes. That's because it's a string. Netscape's "navigator.appName" is the same way -- "Netscape" must be used. Also not that I didn't include an ELSE statement for Netscape or other non-IE browsers. They'll be using a default and the ELSE statement isn't needed. An ExampleBack to our original problem. We're imagining that IE can't display green. We want to use a green background when we can. So, we'll detect IE and let those viewers see a red background while other browser users see a default green background.
<html> The above code is written outside of a function, so it will be executed immediately when the browser reads the code in the <head>. The IF condition tests to see if the "navigator.appName" is "Microsoft Internet Explorer". If it is, an alert() box pops up and a red background color (bgColor) is displayed. If not, a default green background (in the <body> tag) is displayed. Click here to see the above code in action. Try it in both browsers. Play around with browser detection by name. Make the different browsers do different things. You'll be getting a lot of practice in browser detection as we continue learning JavaScript. |
|||
| |||