When I first wrote my abstract for my upcoming RMOUG Training Days 2011 presentation "A First Look at HTML5," I wrote that I'd demonstrate HTML5 in versions of the three most commonly used web browsers: Internet Explorer, Firefox, and Chrome. By the time the abstract was accepted, I had decided to add Safari to the list. I have since decided to add Opera as a fifth web browser. Although Opera doesn't enjoy the widespread use of the first three browsers, it supports some of the HTML5 features as well or better than some of the other browsers and so is useful for a presentation on what HTML5 features will likely be supported. I have already written some posts on HTML5 features and demonstrated those features in the other four browsers. This post "catches up" for Opera and demonstrates the HTML5 Form placeholder support, the Geolocation API, and the Web Storage API in Opera 11.
Opera 11 on Modernizr.com
One of the first things I like to do if using a new web browser and wanting to understand what HTML5 support it has is to visit the Modernizr.com page. In Modernizr: A Handy HTML5 Tool, I looked at the pages rendered at the Modernizr.com site for versions of Internet Explorer, Firefox, Chrome, and Safari. A snasphot of this page rendered on Opera 11 is displayed next.
The screen snapshot demonstrates that Opera 11 provides significant breadth of HTML5 coverage.
Opera 11 and HTML5 Form Placeholder
The next two screen snapshots show for the Opera 11 browser what was shown for the other four browsers in my post HTML5 Form Placeholder Text. As the snapshots demonstrate, Opera 11 does support the placeholder text nicely.
Opera 11 and the Geolocation API
Although it's not technically part of the HTML5 specification, I blogged about the Geolocation API in HTML5 Geolocation API: Your Browser Knows Where You Are. The next series of screenshots demonstrate that this is well supported in Opera. An interesting twist in the Opera sequence is that not only is there a request asks the user if he or she really wants to allow the web site to see the geolocation information, but there is also a follow-on popup window ensuring that the user agrees to terms and conditions associated with this.
To turn off Opera 11's geolocation support, click on "Menu" -> "Settings" -> "Preferences" and then select the "Advanced" tab and select "Network" on the left. At this point, you should be able to uncheck the check box for "Enable geolocation." The next two screen snapshots show this navigation.
I don't show it here, but it's worth noting that when geolocation is disabled for Opera 11 using the setting just shown, the initial page in my example still shows it as enabled, but it simply doesn't work when the button is clicked. The status is updated to "Finished," but never gets to "W o r k i n g . . ." and never displays the latitude or longitude. Two of the web browsers covered previously behaved like this when this feature was turned off.
Opera 11 Web Storage
I blogged about Web Storage in the post HTML5 Local Storage: Web Storage. Opera 11 provides some nice support for Web Storage, which is not technically part of the HTML5 specification anymore, but is treated as part of the bigger "HTML5" concept by many of us. Here are some snapshots showing Opera's useful Web Storage in action. Note that I was able to use HTML source from my local filesystem to see Web Storage work. As I stated in the earlier post, that's not the case for all browsers.
Example Page on Initial Load (No Movie Titles in Storage)
Movie Titles Entered into Form But Not Persisted
"Save" Button Pressed and Movie Titles Persisted
Browser Shut Down and Reloaded
"Load" Button Pressed
To control Web Storage in Opera 11, use its Menu->Settings->Preferences (a screen snapshot in the Geolocation API section shows this), select the "Advanced" tab, and select "Storage" on the left. The ensuing popup is shown next.
Conclusion
As the images in this post have shown, Opera 11 provides excellent support for the "HTML5" features that I have covered so far in blog posts. I intend to regularly include Opera in future posts on browser support for other HTML5 features and I intend to use Opera 11 at my presentation at RMOUG Training Days 2011 next month.
Dustin's Software Development Cogitations and Speculations My observations and thoughts concerning software development (general development, Java, JavaFX, Groovy, Flex, ...). Select posts from this blog are syndicated on DZone and Java Code Geeks and were formerly syndicated on JavaWorld.
Showing posts with label Firefox. Show all posts
Showing posts with label Firefox. Show all posts
Monday, January 10, 2011
Tuesday, January 4, 2011
HTML5 Local Storage: Web Storage
Cookie Monster is not the only one looking past cookies. The Web Storage specification aims to define "an API for persistent data storage of key-value pair data in Web clients." Like the Geolocation API specification I discussed in a previous blog post, this Web Storage specification is separate and distinct from the HTML5 specification (though Web Storage was once part of HTML5). As do many, I lump it in under the "greater" meaning of HTML5 (a bunch of cool new web stuff) rather than strictly adhering to whether it's covered in the HTML5 specification or not. Throughout this post, I may refer to this standardized approach for storing data on the web client as either HTML5 Storage or HTML5 Local Storage, but its official name is Web Storage and it is often referred to as DOM Storage as well.
As stated already, Web Storage (AKA "HTML5 Storage") is designed to store name/value (it calls them key/value) pairs on the web client. The closest analogy may be cookies, but Web Storage (AKA "HTML5 Local Storage") offers numerous advantages over cookies. In this blog post, I look at using Web Storage in Chrome 8, Safari 5, Internet Explorer 8, and Firefox 3.6. Amazingly, even shockingly, the same code used in my example works across all four browsers!
Here is the HTML/JavaScript code listing for my example (it's all encapsulated in a single file called
Storage.html
The code listing above is fairly straightforward, but it does demonstrate use of localStorage.getItem(key) (via array syntax in JavaScript function
For the WebKit-based browsers (Safari and Chrome), I can run this test locally using the file URI scheme and it works properly. For Internet Explorer and Firefox, I was only able to get the above example to work when the
The example in the code above leads to a pretty simple page. The user can click the "Save" button to persist any typed-in movie titles to local persistence. This means that the data is persisted even if the user leaves the page or even closes the browser. Upon returning to the page, the user can click the "Load" button and the previously saved values will be available again. The "Clear" button clears the local persistence. During all of this, two fields at the top indicate whether the browser supports
Static screen snapshots will always lack when compared to seeing dynamic behavior in action, but I attempt to demonstrate this flow through a series of screen snapshots here with the four browsers previously mentioned. The first set of screen snapshots show how the page appears when first presented in Chrome.
Chrome Initial Page Load
When the movie names are typed in and the "Save" button is clicked, the page appears in Chrome as shown next.
Chrome Data Saved to Local Storage
The number of elements in storage is updated to reflect that the ten movie titles have been persisted. When the browser is closed and then reopened, the movie titles are gone, but the number of elements in storage (10) indicates that they are still persisted.
Chrome Closed and Reopened
The user can now click on the "Load" button to have the movie titles reloaded into the fields.
Chrome: Data Reloaded
I have not demonstrated the "Clear" button. It simply clears the fields and clears the entries from the client storage, setting the number of stored elements back to zero. The above screen snapshots were for Chrome. In a very satisfying surprise, the other three browsers I'm covering in this post all behave remarkably consistently. They are shown next with the screen snapshots grouped by browser rather than by step in the demonstration.
Safari 5
Firefox 3.6
Internet Explorer 8
Disabling Web Storage
Local storage provided by standardized implementations of Web Storage provide tremendous potential benefit to users. However, as we have learned with cookies, JavaScript, and the Flash Player, not all users want these things turned on. In this section, I briefly summarize how to disable Web Storage in the browsers covered in this post.
Web Storage capability is disabled in Internet Explorer via "Tools -> Internet Options" ("Advanced Tab" option "Enable DOM Storage" in "Security" section) as shown in the next screen snapshot:
When that box for "Enable DOM Storage" is unchecked (it is checked/enabled by default), the example I have used in this post no longer behaves the same. Instead, it reports that the storage feature is not supported and that the count of stored elements is not applicable. It is shown in the next image.
It is worth noting here that explicitly disabling Internet Explorer's "Enable DOM Storage" support leads to the page reporting that the feature is not supported. I earlier mentioned that Internet Explorer local storage only worked properly when the page was hosted on a web server and accessed via HTTP rather than
The dom.storage.enabled preference configuration controls support for DOM Storage in Firefox. This is changed in the same way that the Firefox geo.enabled preference is changed. To view or change this, type about:config in the field in which URLs are entered, agree to be careful when prompted, and then scroll down to the dom.storage preferences. DOM Storage in Firefox 3.6 is turned on by default as shown in the next screen snapshot. A user can right-click on that preference and choose "Toggle" to turn it to
When this preference is disabled in Firefox, the page shows the same error and "Not Applicable" warning as shown in the Internet Explorer snapshot when it's DOM Storage was disabled.
A similar approach as used to disable Chrome's geolocation support can be used to disable Chrome's DOM Storage support. In particular, the Chrome user can select the "Under the hood" tab from "Options" and click on the "Content settings..." button. Instead of selecting "Location" as is done for disabling geolocation support, "Cookies" should be selected and "Block sites from setting any data" bullet should be set. This appears to disable cookies as well as local storage. In fact, it gave me fits while trying to write this blog and test that out at the same time!
In Chrome's case, it doesn't report that local storage is not supported when the setting of data is disabled. Instead, it simply doesn't store the data no matter how many times I click on the "Save" button. This behavior looks and feels like the Internet Explorer and Firefox behavior when accessing the file via "file://".
A really easy way to disable local storage in Safari is to place it in "Private Browsing" mode. This is demonstrated in the next screen snapshot.
As with Chrome when it is instructed to block sites from setting data, Safari's Private Browsing mode does not lead to the example code knowing that local storage is not supported, but data in the fields is not saved.
Conclusion
Web Storage brings a standardized approach to storing data on the client side. This is another feature of modern web browsers that is bringing the web browser experience closer to the desktop application experience with the ability to store data exclusively on the client side. The standardization of the Web Storage specification can already be enjoyed in the major web browsers as shown with four browsers in this post. The Web Storage API is easy to apply and the consistency across browsers makes it even easier to use.
As stated already, Web Storage (AKA "HTML5 Storage") is designed to store name/value (it calls them key/value) pairs on the web client. The closest analogy may be cookies, but Web Storage (AKA "HTML5 Local Storage") offers numerous advantages over cookies. In this blog post, I look at using Web Storage in Chrome 8, Safari 5, Internet Explorer 8, and Firefox 3.6. Amazingly, even shockingly, the same code used in my example works across all four browsers!
Here is the HTML/JavaScript code listing for my example (it's all encapsulated in a single file called
Storage.html).Storage.html
<html lang="en">
<head>
<meta charset="utf-8" />
<title>HTML5/Web/DOM Storage Demonstrated</title>
<script language="javascript">
/*
* Indicate if this browser supports local storage.
*/
function html5StorageSupported()
{
return ('localStorage' in window) && window['localStorage'] !== null;
}
/*
* Provide number of elements in storage.
*/
function determineNumberStoredElements()
{
return html5StorageSupported() ? localStorage.length : "Not Applicable";
}
/*
* Provide indication on web page of whether this browser supports local storage.
*/
function initialize()
{
document.form1.supported.value = html5StorageSupported() ? "Yes!" : "No (:";
document.form1.numStored.value = determineNumberStoredElements();
}
/*
* Save favorite movies to local storage.
*/
function persistFavoriteMovies()
{
if (html5StorageSupported())
{
for (var i = 1; i <= 10; i++)
{
var movie = document.form1["movie" + i].value;
var storageIndex = "rmoug.td2011.movie." + i;
//alert("Movie #" + i + " [" + storageIndex+ "]: " + movie);
localStorage[storageIndex] = movie;
}
document.form1.numStored.value = determineNumberStoredElements();
}
else
{
alert("Cannot save to local storage because it's not supported.");
}
}
/*
* Load favorite movies from local storage.
*/
function loadFavoriteMovies()
{
if (html5StorageSupported())
{
for (var i = 1; i <= 10; i++)
{
document.form1["movie" + i].value = localStorage["rmoug.td2011.movie." + i];
}
}
}
/*
* Clear favorite movies from both local storage and from form fields.
*/
function clearFavoriteMovies()
{
if (html5StorageSupported())
{
// Clear favorite movies from local storage
localStorage.clear();
// Clear fields of movies content
for (var i = 1; i <= 10; i++)
{
document.form1["movie" + i].value = null;
}
document.form1.numStored.value = determineNumberStoredElements();
}
}
</script>
</head>
<body onload="initialize()">
<h1>HTML5/Web/DOM Storage</h1>
<form name="form1">
<table>
<tr>
<td>Does this browser support local storage?</td>
<td><input type="text" name="supported"></td>
</tr>
<tr>
<td>Number of Stored Elements</td>
<td><input type="text" name="numStored"></td>
</tr>
</table>
<table>
<tr>
<td colspan="2" style="font-weight: bold;" align="center">Favorite Movies</td>
</tr>
<tr>
<td>#1</td>
<td><input type="text" name="movie1"></td>
</tr>
<tr>
<td>#2</td>
<td><input type="text" name="movie2"></td>
</tr>
<tr>
<td>#3</td>
<td><input type="text" name="movie3"></td>
</tr>
<tr>
<td>#4</td>
<td><input type="text" name="movie4"></td>
</tr>
<tr>
<td>#5</td>
<td><input type="text" name="movie5"></td>
</tr>
<tr>
<td>#6</td>
<td><input type="text" name="movie6"></td>
</tr>
<tr>
<td>#7</td>
<td><input type="text" name="movie7"></td>
</tr>
<tr>
<td>#8</td>
<td><input type="text" name="movie8"></td>
</tr>
<tr>
<td>#9</td>
<td><input type="text" name="movie9"></td>
</tr>
<tr>
<td>#10</td>
<td><input type="text" name="movie10"></td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="Load" onclick="loadFavoriteMovies()">
<input type="button" value="Save" onclick="persistFavoriteMovies()">
<input type="button" value="Clear" onclick="clearFavoriteMovies()">
</td>
</tr>
</table>
</form>
</body>
</html>
The code listing above is fairly straightforward, but it does demonstrate use of localStorage.getItem(key) (via array syntax in JavaScript function
loadFavoriteMovies()), localStorage.setItem(key, value) (via array syntax in the JavaScript function persistFavoriteMovies()), localStorage.clear(), and localStorage.length. It also demonstrates how to check whether the browser supports this localStorage attribute.For the WebKit-based browsers (Safari and Chrome), I can run this test locally using the file URI scheme and it works properly. For Internet Explorer and Firefox, I was only able to get the above example to work when the
Storage.html page was accessed on a deployed server. It doesn't really matter which server, but I used GlassFish. Bugzilla@Mozilla's Bug 507361 ("localStorage doesn't work in file:/// documents") documents this issue for Firefox and it also appears to be a known issue for Internet Explorer (including version 9).The example in the code above leads to a pretty simple page. The user can click the "Save" button to persist any typed-in movie titles to local persistence. This means that the data is persisted even if the user leaves the page or even closes the browser. Upon returning to the page, the user can click the "Load" button and the previously saved values will be available again. The "Clear" button clears the local persistence. During all of this, two fields at the top indicate whether the browser supports
localStorage and the number of elements currently stored in local storage.Static screen snapshots will always lack when compared to seeing dynamic behavior in action, but I attempt to demonstrate this flow through a series of screen snapshots here with the four browsers previously mentioned. The first set of screen snapshots show how the page appears when first presented in Chrome.
Chrome Initial Page Load
When the movie names are typed in and the "Save" button is clicked, the page appears in Chrome as shown next.
Chrome Data Saved to Local Storage
The number of elements in storage is updated to reflect that the ten movie titles have been persisted. When the browser is closed and then reopened, the movie titles are gone, but the number of elements in storage (10) indicates that they are still persisted.
Chrome Closed and Reopened
The user can now click on the "Load" button to have the movie titles reloaded into the fields.
Chrome: Data Reloaded
I have not demonstrated the "Clear" button. It simply clears the fields and clears the entries from the client storage, setting the number of stored elements back to zero. The above screen snapshots were for Chrome. In a very satisfying surprise, the other three browsers I'm covering in this post all behave remarkably consistently. They are shown next with the screen snapshots grouped by browser rather than by step in the demonstration.
Safari 5
Firefox 3.6
Internet Explorer 8
Disabling Web Storage
Local storage provided by standardized implementations of Web Storage provide tremendous potential benefit to users. However, as we have learned with cookies, JavaScript, and the Flash Player, not all users want these things turned on. In this section, I briefly summarize how to disable Web Storage in the browsers covered in this post.
Web Storage capability is disabled in Internet Explorer via "Tools -> Internet Options" ("Advanced Tab" option "Enable DOM Storage" in "Security" section) as shown in the next screen snapshot:
When that box for "Enable DOM Storage" is unchecked (it is checked/enabled by default), the example I have used in this post no longer behaves the same. Instead, it reports that the storage feature is not supported and that the count of stored elements is not applicable. It is shown in the next image.
It is worth noting here that explicitly disabling Internet Explorer's "Enable DOM Storage" support leads to the page reporting that the feature is not supported. I earlier mentioned that Internet Explorer local storage only worked properly when the page was hosted on a web server and accessed via HTTP rather than
file://. However, in that case, there was no obvious error. In fact, the page did report that local storage was supported, but the functionality simply did not work. The page would act like it had saved the titles and even updated the number of elements persisted to "10," but then attempting to load them again after closing and opening the browser would fail. This same misbehavior was present in Firefox when the page was accessed via file://.The dom.storage.enabled preference configuration controls support for DOM Storage in Firefox. This is changed in the same way that the Firefox geo.enabled preference is changed. To view or change this, type about:config in the field in which URLs are entered, agree to be careful when prompted, and then scroll down to the dom.storage preferences. DOM Storage in Firefox 3.6 is turned on by default as shown in the next screen snapshot. A user can right-click on that preference and choose "Toggle" to turn it to
false (disabled).When this preference is disabled in Firefox, the page shows the same error and "Not Applicable" warning as shown in the Internet Explorer snapshot when it's DOM Storage was disabled.
A similar approach as used to disable Chrome's geolocation support can be used to disable Chrome's DOM Storage support. In particular, the Chrome user can select the "Under the hood" tab from "Options" and click on the "Content settings..." button. Instead of selecting "Location" as is done for disabling geolocation support, "Cookies" should be selected and "Block sites from setting any data" bullet should be set. This appears to disable cookies as well as local storage. In fact, it gave me fits while trying to write this blog and test that out at the same time!
In Chrome's case, it doesn't report that local storage is not supported when the setting of data is disabled. Instead, it simply doesn't store the data no matter how many times I click on the "Save" button. This behavior looks and feels like the Internet Explorer and Firefox behavior when accessing the file via "file://".
A really easy way to disable local storage in Safari is to place it in "Private Browsing" mode. This is demonstrated in the next screen snapshot.
As with Chrome when it is instructed to block sites from setting data, Safari's Private Browsing mode does not lead to the example code knowing that local storage is not supported, but data in the fields is not saved.
Conclusion
Web Storage brings a standardized approach to storing data on the client side. This is another feature of modern web browsers that is bringing the web browser experience closer to the desktop application experience with the ability to store data exclusively on the client side. The standardization of the Web Storage specification can already be enjoyed in the major web browsers as shown with four browsers in this post. The Web Storage API is easy to apply and the consistency across browsers makes it even easier to use.
Monday, January 3, 2011
HTML5 Geolocation API: Your Browser Knows Where You Are
One of the pieces of functionality commonly discussed when distinguishing HTML5 from previous versions of HTML is the standardization of geolocation via the Geolocation API. Although some browsers supported geolocation functionality prior to HTML5, it is the standardized API that brings new value. This is true of many aspects of HTML5 where HTML5 standardizes across compliant browsers what formerly required browser-specific extensions. The geolocation standardization process is not technically part of the HTML5 specification [it is its own World Wide Web Consortium(W3C) specification], but its timing makes it easy to lump in with other HTML5 enhancements. In other words, it is "HTML5" in the larger sense of "next generation HTML" as opposed to strict HTML5 as outlined in the specification. In this blog post, I briefly look at how the standard geolocation approach can be applied and look at browser support for this feature in Internet Explorer 8, Firefox 3.6, Safari 5, and Google Chrome 8. I also indicate how to turn off geolocation support in browsers that support it.
To illustrate the Geolocation API in action, I use the simple HTML code shown next and call it's file simply Geolocation.html:
Most of the HTML and JavaScript in the example above is to make it easier to see the results. The most important line from a Geolocation API perspective is these lines:
This highlighted code first checks to see if the browser supports the Geolocation API by checking for the existence (support of)
The simple code above typically begins executing in the following order: page load -> verify_geolocation_capability() -> populate "capability" field with text indicating whether geolocation API is enabled or not. Snapshots of the four previously referenced browsers at this point are shown next. Note that the Geolocation API is enabled for Safari 5, Firefox 3.6, and Chrome 8, but is not enabled for Internet Explorer 8.
Safari 5 Supports Geolocation API!
Firefox 3.6 Supports Geolocation API!
Chrome 8 Supports Geolocation API!
Internet Explorer 8 Does NOT Support Geolocation API
The simple HTML application does not do anything further until the user clicks on the button with the text "Get Latitude and Longitude". When that is selected, the code highlighted above relevant to getting position via standardized Geolocation API is executed. In IE's case, the check to make sure that it is supported before trying to access it leads to the Alert popup we expect from looking at the code.
The other three web browsers used in this post do have Geolocation API enabled and so their responses to clicking of the button are more interesting. In fact, their actions at this point are honorable and desirable. It is not surprising that many are uncomfortable with web applications knowing where the user is. Fortunately, the HTML5 Geolocation specification mandates that browsers must seek permission before offering geolocation services to web sites. We see this in action when we click on the button in the three browsers supporting the Geolocation API.
Safari 5 Requests User Permission to Access Location
Firefox 3.6 Requests User Permission to Access Location
Chrome 8 Requests User Permission to Access Location
If the user does not grant this permission, the error handling callback is invoked and provided with an object representing an error. In this simple HTML5 application, the "code" property of that attribute is written to the "capability" field following the "ERROR: " text. This is shown for Safari and Firefox.
Safari 5 Reports Error When User Denies Gelocation Permission
Firefox 3.6 Reports Error When User Denies Gelocation Permission
Let's now be more positive and assume the user does grant the browser to provide geolocation details to the web application. In this simple application, the latitude and longitude are written to the previously empty text fields with the same labels. First, however, because the call is asynchronous, we'll almost always see "Finished" in the "capability" field first and then after some lag of up to a few seconds or more, we'll see "Finished" change to "W o r k i n g . . ." and see the latitude and longitude fields populated. This order occurs because it is almost always the case that the accessing and providing of geolocation data takes longer than it takes for the web browser to execute the next line of JavaScript (setting "capability" field to "Finished"). This phenomenon of asynchronous responses is demonstrated in the following in-order presentation of screen snapshots for Safari and Firefox.
Safari and Firefox both provide more digits in their respective latitudes and longitudes than shown in these edited screen snapshots. When I ran the code above in my browsers on my laptop at home, the latitudes and longitudes returned were scarily close to my home (albeit a street away). How do they do it? Firefox provides a nice FAQ about Firefox gelocation.
Disabling Browser Support for Gelocation Identification
The three browsers referenced in this post that support the Geolocation API meet the standard's requirement of requesting permission before providing location data:
These browsers also provide methods to turn off the capability as the default. I cover how to do this for each of these three browsers in the next section.
To control how Google Chrome handles providing of Geolocation data, click on the wrench icon in the upper right corner of the browser, select "Options", select "Under the Hood" tab, click on "Content settings ..." button, and select "Location". The three options are to always allow all sites access to location data, to be prompted for each site to request access each time it is requested, or to turn it off at all times for all sites. There is an "Exceptions..." button that can be clicked to specify exceptions to the bullet that turns it off for all sites at all times. This is demonstrated in the next screen snapshot.
Safari 5 allows the user to disable location services in general so that the user is not prompted every time a site requests location information. This is done by clicking on the wheel in the upper right corner ("Display a menu of general Safari settings"), selecting "Preferences", clicking on the "Security" lock icon, and unchecking the checkbox labeled "Location Services:" with the option "Allow websites to ask for location information". This is shown in the next screen snapshot.
The Firefox approach for controlling how and when location information is provided to requesting web sites is not difficult, but it does involve a little more effort than that for Safari or Chrome. The Firefox user types "about:config" (without the double quotes) in the field where URLs are typed. This leads to the warning shown in the next screen snapshot.
Bravery pays off here. When that button ("I'll be careful, I promise!") is clicked, a long list of Firefox configuration preferences is presented and they can be changed. The next screen snapshot only shows the configuration this blog post pertains to (geo.enabled), but numerous others are available as well. The values for this preference can be changed to the user's desire. The user clicks on that row and then right-clicks to get the choice of toggling the boolean value or resetting to the default (
Conclusion
The promise of a standardized approach to gelocation is exciting and provides developers an easier approach to making applications richer and more useful to the people using those applications. The standardized API makes developers' lives easier while also potentially benefiting users with location context-based information. This is a huge boon on mobile devices, but can be useful even for laptop and desktop browser users. Besides providing developers with a standard API for delivering features based on location services, another advantage of the Geolocation API is its calling out of compliant browsers' handling of privacy issues related to geolocation. It is comforting to know that major browsers will most likely comply.
Additional References
Dive Into HTML5: You Are Here (and So Is Everybody Else)
Mozilla Developer Center: Using Geolocation
HTML5 Geolocation API is Scaring Me
To illustrate the Geolocation API in action, I use the simple HTML code shown next and call it's file simply Geolocation.html:
<html lang="en">
<head>
<meta charset="utf-8" />
<title>GeoLocation Demonstrated</title>
<script language="javascript">
function verify_geolocation_capability()
{
if (navigator.geolocation)
{
document.form1.capability.value = "Enabled";
}
else
{
document.form1.capability.value = "Not Enabled";
}
}
function display_geolocation_properties(position)
{
document.form1.capability.value = "W o r k i n g . . .";
document.form1.latitude.value = position.coords.latitude;
document.form1.longitude.value = position.coords.longitude;
}
function handle_error(error)
{
document.form1.capability.value = "ERROR: " + error.code;
}
function retrieve_location()
{
if (navigator.geolocation)
{
document.form1.capability.value = "Starting...";
navigator.geolocation.getCurrentPosition(display_geolocation_properties, handle_error);
document.form1.capability.value = "Finished";
}
else
{
alert("This browser does not support geolocation services.");
}
}
</script>
</head>
<body onload="verify_geolocation_capability()">
<h1>Latitude and Longitude</h1>
<form name="form1" id="form1">
Geolocation Capability: <input type="text" name="capability" value="Unknown">
<p />
Latitude: <input type="text" name="latitude">
<p />
Longitude: <input type="text" name="longitude">
<p />
<input type="button" name="submit" value="Get Latitude and Longitude" onclick="retrieve_location()">
</form>
</body>
</html>
Most of the HTML and JavaScript in the example above is to make it easier to see the results. The most important line from a Geolocation API perspective is these lines:
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(display_geolocation_properties, handle_error);
}
This highlighted code first checks to see if the browser supports the Geolocation API by checking for the existence (support of)
naviator.geolocation. If it does exist (is supported), then the code accesses its getCurrentPosition function and passes two function names to it as arguments. The first function, display_geolocation_properties is used for successful responses and the second function name, handle_error, is used to process error responses. As will be shown in later screen snapshots in this post, these methods are invoked asynchronously.The simple code above typically begins executing in the following order: page load -> verify_geolocation_capability() -> populate "capability" field with text indicating whether geolocation API is enabled or not. Snapshots of the four previously referenced browsers at this point are shown next. Note that the Geolocation API is enabled for Safari 5, Firefox 3.6, and Chrome 8, but is not enabled for Internet Explorer 8.
Safari 5 Supports Geolocation API!
Firefox 3.6 Supports Geolocation API!
Chrome 8 Supports Geolocation API!
Internet Explorer 8 Does NOT Support Geolocation API
The simple HTML application does not do anything further until the user clicks on the button with the text "Get Latitude and Longitude". When that is selected, the code highlighted above relevant to getting position via standardized Geolocation API is executed. In IE's case, the check to make sure that it is supported before trying to access it leads to the Alert popup we expect from looking at the code.
The other three web browsers used in this post do have Geolocation API enabled and so their responses to clicking of the button are more interesting. In fact, their actions at this point are honorable and desirable. It is not surprising that many are uncomfortable with web applications knowing where the user is. Fortunately, the HTML5 Geolocation specification mandates that browsers must seek permission before offering geolocation services to web sites. We see this in action when we click on the button in the three browsers supporting the Geolocation API.
Safari 5 Requests User Permission to Access Location
Firefox 3.6 Requests User Permission to Access Location
Chrome 8 Requests User Permission to Access Location
If the user does not grant this permission, the error handling callback is invoked and provided with an object representing an error. In this simple HTML5 application, the "code" property of that attribute is written to the "capability" field following the "ERROR: " text. This is shown for Safari and Firefox.
Safari 5 Reports Error When User Denies Gelocation Permission
Firefox 3.6 Reports Error When User Denies Gelocation Permission
Let's now be more positive and assume the user does grant the browser to provide geolocation details to the web application. In this simple application, the latitude and longitude are written to the previously empty text fields with the same labels. First, however, because the call is asynchronous, we'll almost always see "Finished" in the "capability" field first and then after some lag of up to a few seconds or more, we'll see "Finished" change to "W o r k i n g . . ." and see the latitude and longitude fields populated. This order occurs because it is almost always the case that the accessing and providing of geolocation data takes longer than it takes for the web browser to execute the next line of JavaScript (setting "capability" field to "Finished"). This phenomenon of asynchronous responses is demonstrated in the following in-order presentation of screen snapshots for Safari and Firefox.
Safari and Firefox both provide more digits in their respective latitudes and longitudes than shown in these edited screen snapshots. When I ran the code above in my browsers on my laptop at home, the latitudes and longitudes returned were scarily close to my home (albeit a street away). How do they do it? Firefox provides a nice FAQ about Firefox gelocation.
Disabling Browser Support for Gelocation Identification
The three browsers referenced in this post that support the Geolocation API meet the standard's requirement of requesting permission before providing location data:
A conforming implementation of this specification must provide a mechanism that protects the user's privacy and this mechanism should ensure that no location information is made available through this API without the user's express permission. ... User agents must not send location information to Web sites without the express permission of the user. User agents must acquire permission through a user interface, unless they have prearranged trust relationships with users.
These browsers also provide methods to turn off the capability as the default. I cover how to do this for each of these three browsers in the next section.
To control how Google Chrome handles providing of Geolocation data, click on the wrench icon in the upper right corner of the browser, select "Options", select "Under the Hood" tab, click on "Content settings ..." button, and select "Location". The three options are to always allow all sites access to location data, to be prompted for each site to request access each time it is requested, or to turn it off at all times for all sites. There is an "Exceptions..." button that can be clicked to specify exceptions to the bullet that turns it off for all sites at all times. This is demonstrated in the next screen snapshot.
Safari 5 allows the user to disable location services in general so that the user is not prompted every time a site requests location information. This is done by clicking on the wheel in the upper right corner ("Display a menu of general Safari settings"), selecting "Preferences", clicking on the "Security" lock icon, and unchecking the checkbox labeled "Location Services:" with the option "Allow websites to ask for location information". This is shown in the next screen snapshot.
The Firefox approach for controlling how and when location information is provided to requesting web sites is not difficult, but it does involve a little more effort than that for Safari or Chrome. The Firefox user types "about:config" (without the double quotes) in the field where URLs are typed. This leads to the warning shown in the next screen snapshot.
Bravery pays off here. When that button ("I'll be careful, I promise!") is clicked, a long list of Firefox configuration preferences is presented and they can be changed. The next screen snapshot only shows the configuration this blog post pertains to (geo.enabled), but numerous others are available as well. The values for this preference can be changed to the user's desire. The user clicks on that row and then right-clicks to get the choice of toggling the boolean value or resetting to the default (
true). If the user did turn it off, the Status column indicates that the property is "user set". The screen snapshot that follows shows this more clearly.Conclusion
The promise of a standardized approach to gelocation is exciting and provides developers an easier approach to making applications richer and more useful to the people using those applications. The standardized API makes developers' lives easier while also potentially benefiting users with location context-based information. This is a huge boon on mobile devices, but can be useful even for laptop and desktop browser users. Besides providing developers with a standard API for delivering features based on location services, another advantage of the Geolocation API is its calling out of compliant browsers' handling of privacy issues related to geolocation. It is comforting to know that major browsers will most likely comply.
Additional References
Dive Into HTML5: You Are Here (and So Is Everybody Else)
Mozilla Developer Center: Using Geolocation
HTML5 Geolocation API is Scaring Me
Subscribe to:
Comments (Atom)





















































