Session 18 :
Introduction
Consider an e-mail client, such as Gmail. To log in to your mail account in Gmail, you need to enter your username and password.
As shown in figure 18.1, the Stay signed in check box, specifies that the login details, such as Username and Password, should be remembered by the computer.
Traditionally, over the last few decades, Web applications have been using cookies to store small amounts of information on a user’s computer. A cookie is a file that stores user-related information and may either be temporary or permanent. Thus, in this case, a cookie can be created for login details which can be saved for a specified period on a user’s computer.
However, the drawbacks of cookies are as follows:
Cookies slow down the performance of Web application, as they are included with every HTTP request.
Cookies cannot be considered as safe means for transmission of sensitive data.
Cookies cannot store large amount of information, as they have a limitation of size of 4 KB.
To overcome these drawbacks and offer a solution to store data on the client-side, W3C has designed a specification named Web Storage API.
The Web storage provides the functionality using which data can be stored on the client-side for a session or beyond the session.
Web Storage in HTML5
Web storage is a W3C specification. It provides functionality for storage of data on the client-side that is on user’s machine. This data can cater for both temporary as well as permanent needs. Certain browsers also refer to it as ‘DOM Storage’. The advantage of such storage is that it offers more control than traditional cookies, and is easy to work with.
Web storage was originally a part of the HTML5 specification, but now it is present in a separate specification. It enables to store a maximum of 5 MB of information per domain.
HTML5 Web applications make use of Web storage to implement client-side persistent storage.
18.2.1 Web Storage versus Cookies
There are some key differences between cookies and Web storage that are as follows:
Cookies are meant to be read on the server-side, whereas Web storage is available only on the client-side. The server cannot read or write to it directly.
Cookies are sent along with each HTTP request to the server, whereas Web storage data is not carried over to the server.
Cookies can result in bandwidth overhead and thus lead to high costs, as they are sent with each HTTP request. The Web storage is stored on the user’s hard drive, so it costs nothing to use.
As mentioned earlier, with cookies, the information data that could be stored is 4 KB, whereas with Web storage, a large amount of data can be stored upto 5 MB.
18.2.2 Browser-specific Web Storage
Web storage is browser-specific. If a user visits a site in Google Chrome, any data will be stored to Google Chrome’s Web storage store. Similarly, if the user revisits that same site in Firefox, the data saved earlier through Google Chrome will be unavailable. The location where the Web storage data is stored depends on the browser. Each browser’s storage is separate and independent, even if it is present on the same machine.
HTML5 Web storage is implemented natively in most Web browsers, so one can use it even when a third-party browser plug-in is not available.
Exploring Web Storage
The two types of HTML5 Web storage are namely, session storage and local storage. Both session and local storage enable to store around 5 MB of data per domain. Before going into the details of these types, you need to determine, if the current version of your browser has support for HTML5 Web storage.
To check for browser support of HTML5 Web storage, a property named localStorage or sessionStorage is available as a global variable for the window object. If there is no support, the localStorage or sessionStorage property will be undefined.
Code Snippet 1 demonstrates the script to check the support for HTML5 Web storage in the browser.
Code Snippet 1:
<!DOCTYPE html>
<html>
<head>
<title>Support for Web Storage</title>
<script>
function checkSupport()
{
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !== null)
{
alert(“Your browser supports Web Storage”);
return;
}
alert(“Your browser does not support Web Storage”);
}
</script>
</head>
<body onload=”checkSupport();”>
</body>
</html>
Here, in the code, the if statement checks whether a property named sessionStorage exists in the global window object. If the property exists, it means that session storage is supported and an appropriate message is displayed to indicate the same. If however, the property does not exists, it means session storage is not supported on that browser, and an appropriate message is displayed to indicate the same.
Figure 18.2 shows the Web storage support.
Figure 18.2: Web Storage Support
18.3.1 Session Storage
Session storage keeps track of data specific to one window or tab and discards it as soon the user closes the tab (or window) that he/she was working with. Thus, even if you are visiting the same site in two different windows, each window will have its own individual session storage object. This means that each window contains separate session storage object with distinct data. Session storage lasts for the entire duration of the session and hence, is not persistent.
Session storage makes use of named key/value pairs. The data is stored using the named key, whereas the data is retrieved by referring to that key. Both the key-value pairs are enclosed within double quotes.
The key is a string, whereas the value stored in the key can be of any type of data, such as string, boolean, integer, or float. Regardless of the type of data that is stored, it is actually stored internally as a string.
Therefore, storing and retrieving data of other types requires the use of functions to convert them into the appropriate data types.
For example, the function, parseInt() is used to convert data into an appropriate JavaScript data type.
Key Value
Name Sarah
book C Programming
Email info@me.com
car Toyota Innova
age 28
uservalid true
There are several operations that can be performed with the sessionStorage object. These operations are described as follows:
Storing and retrieving data
The setItem() and getItem() methods are used to store and retrieve data from session storage respectively.
The syntax to use the setItem() and getItem() methods is as follows:
Syntax:
To assign data
sessionStorage.setItem(key, value);
where,
key: Is the named key to refer to the data
value: Is the data to be stored
To retrieve data
var item = sessionStorage.getItem(key);
where,
item: Is the variable into which the data will be saved
key: Is the named key to refer to the data
<!DOCTYPE html>
<html>
<head>
<title>Working with Session Storage</title>
<script>
function testStorage()
{
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !== null)
{
sessionStorage.setItem(‘name’, ‘Sarah’);
alert(‘The name is: ‘ + sessionStorage.getItem(‘name’));
}
}
</script>
</head>
<body onload=” testStorage();”>
</body>
</html>
Key names need not necessarily be given as strings. Even, a number can be specified as a key name, though internally while storing, it will be converted to a string.
Code Snippet 3 shows the script that uses number as the key.
Code Snippet 3:
<script>
function testStorage()
{
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !== null)
{
sessionStorage.setItem(6, ‘The book was wonderful’);
var feedback = sessionStorage.getItem(6);
alert(feedback);
}
}
</script>
Here, in the code, the key is set to a numeric value 6, but that does not mean that it is the sixth key. The name of the key is defined as 6 that is stored internally in the browser. The getItem() method is used to retrieve the value stored with that key. Finally, the value having the key as 6 is displayed in the alert window.529 of 590 Concepts Session 1HTML5 Web Storage
Figure 18.4 shows the output that retrieves value stored at the key, 6.
Figure 18.4: Output – Retrieves Value Stored at Key 6
Similar to other JavaScript objects, the sessionStorage object can be treated as an associative array. Instead of using the getItem() and setItem() methods, an array subscript can be used to retrieve and assign the data. For example, sessionStorage.setItem(‘name’,’John’); can be written as sessionStorage[‘name’] =’John’;
Similarly, alert (sessionStorage.getItem(‘name’)); can be written as alert (sessionStorage[‘name’]);
As mentioned earlier, it is also possible to store non-string values into session storage.
Code Snippet 4 demonstrates the storage of an integer value for age and is later retrieved by using parseInt() method along with the getItem() method.
<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8”>
<title> Session Storage </title>
<script>
function store() {
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !== null) {
var name = document.getElementById(‘name’).value;
sessionStorage.setItem(‘username’, name);
var data = sessionStorage.getItem(‘username’);
A database is an organized collection of data. Databases, such as relational database stores the data in the form of tables. A table comprises rows and columns that are used to store data. The representation of data from a table is in the form of records.
HTML5 has introduced a new Web Storage API which can host Web databases locally within the user browser. However, Web databases are not like relational databases in terms of functionality.
Indexed Database API is a specification also known as IndexedDB. It is basically an object store that can be used to store and manipulate data on the client-side. The object store is the primary storage mechanism that stores the object in the database managed locally within the browser. It enables to create an object store of a particular type in which objects can be persisted using JavaScript. Thus, IndexedDB enables to create Web applications with rich query abilities and which can work both online and offline.
IndexedDB supports two types of API namely, synchronous and asynchronous. The synchronous API can be used with WebWorkers, whereas asynchronous API can be used for Web applications. Currently, no major browsers provide the support for synchronous API.
The IndexedDB API is implemented using window.indexedDB object. As the current specification is still in the evolving stage, browsers implement the IndexedDB object with their own prefixes. For example, Chrome browser uses the webkit prefix, whereas Mozilla supports –moz prefix.
IndexedDB API
Some of the basic constructs of IndexedDB API are as follows:
Database - The IndexedDB database comprises more than one object store. Each database contains a name that identifies the origin of the database and a version number which identifies the lifetime of the database.
Object Store - Object store is the main mechanism to store data in a database. They hold the data stored in the database in the form of records.
Keys - Each record stored in the database is identified by a unique key.
Values - Values are the data stored in the records.
Key Path - A key path is a string that defines how the browser should extract key from a value. The key from a value can be extracted either in the object store or index. An empty string, a JavaScript identifier, and so on is some of the valid key paths.
Index - It is used when the data from the object store is retrieved based on some other values other than a key. It is a specialized object store which searches for records in another object store known as referenced object store.
Transaction - Any addition or retrieval of the data in a database is performed by using transaction. In other words, it is a mechanism used for interacting with the database. Each transaction has a mode, scope, and a request list. The mode determines the type of transaction that can be performed, scope identifies the object store on which the transaction will be performed, and finally request list determines the requests that have been made.
Requests - Operations, such as reading or writing on the database is performed using a request. Each request contains attributes, such as flag, source object, result, and error.
Cursor - Cursor is a mechanism used to retrieve multiple records from a database.
Key Range - Records from the object stores and indexes are retrieved using keys or key ranges. A key range refers to retrieval of data between specified bounds based on the keys
Implementing IndexedDB API
The steps to implement the IndexedDB API in a Web application are as follows:
Open a database
Create an object store
Start a transaction
Perform some database operations, such as add and retrieve
Work with the retrieved results
Opening a Database
Code Snippet 7 shows the code to open a database.
Code Snippet 7:
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
var request = indexedDB.open(“CompanyDB”, 1);
request.onsuccess = function (event) {
. . .
};
request.onerror = function (event) {
console.log(“IndexedDB error: “ + event.target.errorCode);
};
Creating the Object Store
The structure of IndexedDB database facilitates the storage of multiple object stores. In other words, there can be more than one object stores in the database. Object store is created using createObjectStore() method. The createObjectStore() methods accepts two arguments namely, the store name and a parameter object. The parameter object is used for defining an optional property which is important. In this case, a key path is defined that is used for identifying unique objects in the object store. For example, an employee store contains the id property as key path, which will be unique for each object and must be present for each object.
HTML5 Web Storage Limited Code Snippet 9 demonstrates the code to create an object store named employee in the CompanyDB database.
Code Snippet 9:
var employeeData = [
{ name: “John Smith”, email: “john@company.com” },
{ name: “Jill Patrick”, email: “jill@company.com” },
{ name: “Rock Ethan”, email: “rock@company.com” },
{ name: “Daniel Andrew”, email: “daniel@company.com” }
];
var objectStore = db.createObjectStore(“employee”, {
keyPath: “id”, autoIncrement: true });
for (i in employeeData) {
objectStore.put(employeeData[i]);
alert(“Record added”);
}
The code creates an array named employeeData containing name and e-mail values. Then, the createObjectStore() method creates an employee store with its key path set to id attribute. The key path is used with autoIncrement option that automatically generates id for each of the objects. All the individual objects in the object store are identified based on the id. Finally, the for..in loop stores the data in the employee object store.
Creating a Transaction
To perform database operation, such as retrieving data from the object store, IndexedDB provides a IDBTransaction object. This object can be created in three mode namely, read-only, read-write, and snapshot. The read-write mode is used to update the object, whereas read-only mode is used for other operations.
Code Snippet 10 demonstrates the code to retrieve data from the employee object store using the get() function of the transaction object.
Code Snippet 10:
var trans = db.transaction([“employee”], IDBTransaction.READ_ WRITE).objectStore(“employee”);
var request = trans.get(2);
request.onerror = function(event) {
// Handle errors!
};
request.onsuccess = function(event) {
// Do something with the request.result!
alert(“Name: “ + request.result.name);
};
In the code, the transaction() method accepts two parameters. The second parameter is optional. The first parameter is the list of the object stores that are extended by the transaction object. In this case, there is a single object store named employee, created in the database. The optional second parameter specifies the type of the transaction, that is, read-only, read-write, or snapshot. Here, the transaction type is defined as IDBTransaction.READ_WRITE. This type allows reading as well as writing in the database. The employee object store is retrieved from the transaction object on which operations are performed. Here, the get() method is invoked on the employee object store which returns the value against the key path 2. Finally, the result of the get() method is stored in the request object on which callback functions, such as onsuccess and onerror are invoked.
Opening a Cursor
Cursor is used to retrieve multiple records from an object store. They can be used when the value of key path is not known. They are part of a transaction and are opened for a particular object store.
540 of 590 Concepts Session 1HTML5 Web Storage V 1.1 © zetutorials Limited
Code Snippet 11 demonstrates the code to retrieve multiple records from the employee object store.
Code Snippet 11:
store = db.transaction(“employee”).objectStore(“employee”);
store.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert(“Name for id “ + cursor.key + “ is “ + cursor.value.name);
cursor.continue();
}
};
Native Apps HTML5 Apps
Native Apps runs on iOS and Android devices that can be downloaded or purchased from the online app stores. HTML5 Apps runs on a Web server, usually in a Web browser.
Native Apps use programming language, such as Java for Android devices and Objective C for iOS devices. Web developers use HTML, JavaScript, and CSS. They need to acquire the skills of Java and objective C for writing native applications.
Advantages of HTML5 Apps
The main advantage of using HTML5 is to create applications that execute on a wide range of devices easily. App development on HTML5 is cheaper as compared to native app development. Developers do not have to learn any new programming language and the development becomes much easier.
There are many reasons to develop HTML5 applications rather than native applications. Some of the reasons are as follows
Users cannot identify the differences
There are many instances where the users cannot identify whether they are working on a hybrid HTML5-native application or a fully native application or an HTML5 application.
Users adjust styles for devices
HTML5 apps can be viewed on any devices that contains Web browser. Users can also use CSS3 for applying styles to change the look according to their requirements. HTML5 apps look similar to Web pages by using the same code.
Upcoming functionalities
HTML5 does not support all features on a device, but it is coming up with new functionalities. There are several APIs that exist for working on local databases, Web storage, drag-and-drop, offline Web pages, and many more. New APIs are being planned in future to provide Web pages access to the software and hardware of a device.
Improving performance
Many developers learn new methods to improve the performance of Web pages. These same methods are useful to mobile HTML5 apps. There are many apps, such as timer, mail, databases, and news apps that need not be faster.
Independent device
HTML5 apps work on mobile devices as well as Web browsers, as it is important for development purpose. There are millions of laptop and desktop users than mobile users. If the developers want that their application to be used by a large number of users, then they should design and develop the application for both mobile users as well as desktop users.
Developers are not locked in app stores
There are a number of app stores existing for Android and BlackBerry. If developers wish to sell the apps, then they are required to provide them into as many stores or marketplaces as possible. By using HTML5, developers are not restricted to an app store. Instead, they can create applications and sell them like any other Web application.
HTML5 app acts a substitute to native apps, though in several conditions, native apps can be used for better purpose. Developers can create hybrid applications that are a combination of native and HTML apps.
18.6.3 Advantages of Native Apps
The major advantage of native apps over HTML5 apps is that they are faster than HTML5 apps. Similar to normal Web pages, HTML5 apps are slow, because these apps work on HTTP that uses a request/response cycle mechanism. When an HTTP request is made, it takes more time for the applications to execute as it has to wait for the request to go and return back with a response.
Advantages of Native Apps
The major advantage of native apps over HTML5 apps is that they are faster than HTML5 apps. Similar to normal Web pages, HTML5 apps are slow, because these apps work on HTTP that uses a request/response cycle mechanism. When an HTTP request is made, it takes more time for the applications to execute as it has to wait for the request to go and return back with a response.
54of 590 Concepts Session 1HTML5 Web Storage V 1.1 © zetutorials Limited
Native apps provide many more benefits over HTML5 apps. These benefits are as follows:
Providing access to device hardware
Many mobile devices contain hardware, such as accelerometer, GPS, a camera, and so on. The GPS is accessible through Geolocation API. At present, there are no APIs available for accelerometers, cameras, or any other device hardware for HTML5 apps.
Uploading Files
Native apps can access the file system in Android and some files in iOS. However, the HTML5 file API does not work on Android or iOS.
Push Notifications
The push notifications are sent always with an open Internet Protocol (IP) connection to applications on the iOS device. Android also has a same feature named Cloud to Device Messaging.
Accessing device files
Native apps communicate with files on devices, such as contacts and photos. However, these files cannot be seen from HTML5 apps.
Superior graphics than HTML5
HTML5 has a <canvas> element, but it will not be able to create a full 3D experience.
Offline access
HTML5 provides access to offline Web applications. However, a native app is stored on local machine, so the users do not require access to the Web to work with the application.
In-app purchasing and advertising
HTML5 apps allow developing in-app stores and advertising. Native apps have these features pre-built in them through app stores. Selling the apps in app store is easy, as HTML5 apps are Web pages that are difficult to sell.
Native apps have an additional benefit, that is trust. Several users are comfortable using application downloaded from app stores than using a Web page. These app stores are preferred than search engines, by the users for finding tools.
54of 590 Concepts Session 1HTML5 Web Storage V 1.1 © zetutorials Limited
18.6.4 Converting HTML5 Apps to Native Apps
Users have a choice of developing their application in HTML5 and then converting them into a native app. This choice has many combined benefits of HTML5 apps and native apps. Users can use tools to convert HTML5 app to a native app.
The following are the best tools used for converting an HTML5 app to native app:
PhoneGap
PhoneGap is an HTML5 app that allows the user to create native apps with Web technologies and is accessible to app stores and APIs. PhoneGap controls the Web technologies.
Appcelerator
Appcelerator is a cross-platform mobile application development support. It allows the users to create Android, iOS, and mobile Web apps. Native applications are developed using a JavaScript code base with Eclipse as the IDE.
Converting HTML5 Apps to Native Apps
Users have a choice of developing their application in HTML5 and then converting them into a native app. This choice has many combined benefits of HTML5 apps and native apps. Users can use tools to convert HTML5 app to a native app.
The following are the best tools used for converting an HTML5 app to native app:
PhoneGap
PhoneGap is an HTML5 app that allows the user to create native apps with Web technologies and is accessible to app stores and APIs. PhoneGap controls the Web technologies.
Appcelerator
Appcelerator is a cross-platform mobile application development support. It allows the users to create Android, iOS, and mobile Web apps. Native applications are developed using a JavaScript code base with Eclipse as the IDE.
No comments:
Post a Comment