Working with Different Browsers - Advanced JavaScript - JavaScript, 20 Lessons to Successful Web Development (2015)

JavaScript, 20 Lessons to Successful Web Development (2015)

PART II Advanced JavaScript

LESSON 18 Working with Different Browsers

image

To view the accompanying video for this lesson, please visit mhprofessional.com/nixonjavascript/.

In the beginning there was the Mosaic web browser and all web pages displayed the same. Then along came Netscape Navigator and there were now two competing standards. Microsoft wasn’t happy about this and so it also released a browser called Internet Explorer (IE), which made web developing something you had to do three times to ensure your sites looked good on all browsers. However, because Microsoft gave the browser away, it effectively killed off the other two browsers, and so compatibility stopped being an issue and the world of web developing settled down for a few years.

But then there came the descendant of Netscape, Mozilla Firefox, which made rapid inroads into the market share of IE because it was fast and slick and had many new features. And, because it approached things from a different point of view, web pages started to look different again on different browsers.

At the same time, other browsers such as Opera and Safari entered the fray, followed by the likes of Google Chrome, and then the iOS and Android browsers. Fortunately, though, all the new browsers tended to agree with the W3C (Worldwide Web Consortium) on how HTML should be handled, so most of the incompatibilities were considered by developers to be the fault of IE. Therefore, code generally would be written once for non-IE browsers, and then had to be tweaked (often a considerable process on a large site) to run the same on IE.

However, because of the overwhelming support of competing browsers causing IE to lose market share, over the last couple of iterations, Internet Explorer has become faster, more sophisticated, and ever more compatible with the industry standards. Therefore, now we find ourselves back in a position where developers can spend most of their time simply designing, and not so much catering for inconsistencies.

Nevertheless, browsers are massively powerful applications packed with hundreds of thousands of lines of complex code, and there will probably always be a few differences between major browsers, and as a developer you need to have a way to distinguish between browsers (and even versions of browsers) to tailor your code where necessary. In this lesson I show you how to do just that, as well as how to read and make use of the query string (the alphanumeric data that is often attached to URLs).

The User Agent String

Every web page request has a user agent string passed with it by well-behaved browsers. You can usually rely on this string to determine information about the user’s computer and web browser. However, some browsers allow the user to modify the user agent string, and some web spiders and other ″bots″ use misleading user agents, or even don’t provide any user agent string.

Nevertheless, on the whole, it is a very handy item of data to make use of, and takes a form such as the formidable following user agent string:

image

Each string can be different from any other due to the way the browser is configured, its brand and version, the add-ons in it, the operating system used, and so on. In the instance of the preceding string, it states that the browser is Internet Explorer 10, it is broadly compatible with version 5 of Mozilla-based browsers such as Firefox, the operating system is Windows 7 (NT 6.1), the layout engine is Trident, .NET framework 2.0.50727 is running on the computer, and the browser is a Windows-On-Windows program (a 32-bit application running on a 64-bit processor).

Most of these you can normally ignore, but the most useful piece of information is that the browser is Internet Explorer, because sometimes you need to tailor code to specific browsers, and most frequently that has been the case with Internet Explorer because of a history of incorporating nonstandard features.

The GetBrowser() Function

To extract this information from the user agent string, you can use a function such as the following, which checks a couple of other useful properties as well as userAgent:

image

image

This code determines whether the browser is an early version of Internet Explorer by checking the document.all property, which exists only in IE. Then it interrogates window.opera to see whether the browser is an early version of Opera. After that, the user agent string is tested for all major browsers such as newer versions of Opera and IE, as well as Google Chrome, Apple Safari, Mozilla Firefox, Google Android, and various Apple iOS devices.

The command that interrogates the user agent string is the following, which uses the indexOf() function to find out whether the value in check is contained in userAgent (returning true if so):

return navigator.userAgent.indexOf(check) != -1

Using the Function

You can copy this function into your own code and simply make a call such as the following to assign the current browser name to the variable Browser:

Browser = GetBrowser()

Figure 18-1 shows this function being called using the useragent.htm file from the companion archive.

image

FIGURE 18-1 Returning the current browser name

image

Did you notice how the NavCheck() function was placed inside the GetBrowser() function? This is because it is called only by that function and so putting it in the function keeps the code tidy and easy to follow. However, if your code ever needs to call the NavCheck() function directly, you should move it back outside again.

The Query String

The query string is the part of a URL that follows the document file name and is preceded with a ? character. Typically, it is used to send Get requests from a form to a web server. A Get request is one where all the data being sent to the sever is in clear view (as opposed to a Post request that sends the data invisibly, attaching nothing to the URL).

A typical URL with a Get request might look like the following search request made to the Google search engine:

http://www.google.com/search?q=query+string&ie=utf-8

The query string here is the part after the ?, as follows:

q=query+string&ie=utf-8

In this instance, the query string has two key/value pairs (separated by the & character):

q = query+string

ie = utf-8

image

Query strings are almost always escaped so that any special characters are replaced with escape characters, and in this instance, the space character has become a + character (but could have also been encoded as %20 like in q=query%20 string).

The GetQueryString() Function

However, it isn’t only web servers that can process Get requests, because you can read query strings from JavaScript too, using a function such as this:

image

This function accesses the query string in window.location.search. But because a ? character is always included (even though it’s not actually part of the query string), the substr() function is called with an argument of 1, which passes on everything but the first character to the split()function:

var parts = window.location.search.substr(1).split(′&′)

The split() function then splits the string at all occurrences of &, placing the parts into the array parts. Then a for() loop iterates through the parts, separating each into key/value pairs by splitting them at occurrences of the = character. The string value in parts[i] is then replaced with an array containing the key in its first element and the value in its second element:

image

Finally, the parts array is returned:

return parts

Using the Function

To obtain the keys and values in the query string, all your code has to do is call this function as follows:

Query = GetQueryString()

The array Query will now contain an array of key/value pairs, with each key and value stored in a sub-array for each element. Therefore, you can iterate through the array, for example, like this (liberally whitespaced for clarity):

image

Because query strings have escaped values, when you actually want to use a key or value, you will need to decode it like this:

image

These lines assign the first key and its value to Key0 and Val0, first putting them through the decodeURIComponent() function. The second key and value (if any) could be extracted like this (and so on):

image

Figure 18-2 shows a query string of ?a=1&b=2 appended to the example file query.htm (from the companion archive). If you wish to test this file, remember to add that string to the end of the URL in the address bar, like this:

query.htm?a=1&b=2

image

FIGURE 18-2 Reading and displaying query string values

image

You may sometimes see the deprecated unescape() function used instead of decodeURIComponent(). But unescape() is in the process of being dropped, so you should use decodeURIComponent() instead to ensure future compatibility for your code.

Summary

Now that you know how to determine the browser that is running your code, you have the ability to modify your pages accordingly. For example, on a device that has a phone included such as an iPhone or Android phone, you could highlight any phone numbers to make them easily selectable. Or you can reformat the layout of a website to better fit a much smaller screen.

You can now also read the contents of query strings to see whether visitors have come to your web page from a particular search engine, and can also modify your display accordingly, perhaps by highlighting any keywords that were searched for.

Therefore, now that you have all the basics of JavaScript web development under your belt, in the remaining pair of lessons, we’ll move on to some advanced (but fun) programming that will really make your websites stand out from the crowd, starting with implementing interrupt-driven code.

Self-Test Questions

Using these questions, test how much you have learned in this lesson. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in Appendix A.

1. What is the best way to test whether a browser is Internet Explorer?

2. What is the best way to test whether a browser is Opera?

3. With which object can you test for all other browser types?

4. What is a query string?

5. What character immediately precedes a query string in a URL?

6. Which character separates key/value pairs in a query string?

7. How is a space character represented in a query string?

8. Which property contains the current query string?

9. With which function can you separate key=value substrings from a query string into an array?

10. Given an array of key=value substrings, how can you turn each string element into a sub-array containing the key in its first element and value in its second element?