HTML5 XP - Session 18
HTML5 XP - Session 18
nl
O
se
U
tre
en
Session: 18
C
h
ec
nl
Explain session storage
O
Explain local storage
se
U
Explain the Indexed DB API
tre
Describe a native app
en
Explain the difference between native apps and HTML5 apps
C
Describe the advantages of native and HTML5 apps
h
List the steps to convert HTML5 apps to native apps
ec
pt
rA
Fo
O
cookies to store small amounts of information on a user’s computer.
se
A cookie is a file that stores user-related information and may either be
temporary or permanent.
U
A cookie can be created for login details which can be saved for a specified
tre
period on a user’s computer.
en
C
Drawbacks of cookies are as follows:
h
Cookies slow down the performance of Web application, as they are included
ec
of size of 4 KB
W3C has designed a specification named Web Storage API which offer a solution
to store data on the client-side
© Aptech Ltd. HTML5 Web Storage / Session 18 3
y
nl
O
Is a W3C specification and certain browsers refer to it as ‘DOM Storage’.
se
U
Provides functionality for storage of data on the client-side that is on user’s
machine.
tre
en
Stores data that can cater for both temporary as well as permanent needs.
C
Offers more control than traditional cookies, and is easy to work with.
h
ec
nl
O
Cookies are meant to be read on the server-side, whereas Web storage is
se
available only on the client-side.
U
Cookies are sent along with each HTTP request to the server, whereas Web
tre
storage data is not carried over to the server.
en
Cookies 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
C
drive, so it costs nothing to use.
h
ec
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.
pt
rA
Fo
O
Each browser’s storage is separate and independent, even if it is present on the
se
same machine.
U
HTML5 Web storage is implemented natively in most Web browsers, so one can
use it even when third-party browser plug-in is not available.
tre
Following table lists the support of various browsers for HTML5 Web storage:
en
Browser
C
Version
h
ec
IE 8.0+
pt
Firefox 3.6+
rA
Safari 4.0+
Fo
Chrome 5.0+
Opera 10.5+
se
U
Both session and local storage enable to store around 5 MB of data per domain.
tre
To check for browser support of HTML5 Web storage, a property named
en
localStorage or sessionStorage is available as a global variable for the window
object.
C
If there is no support, the localStorage or sessionStorage property will be
h
undefined.
ec
pt
rA
Fo
y
Code Snippet demonstrates the script to check the support for HTML5 Web
nl
storage in the browser.
O
<!DOCTYPE html>
se
<html>
<head>
U
<title>Support for Web Storage</title>
<script>
tre
function checkSupport() {
if ((‘sessionStorage’ in window) && window[‘sessionStorage’]
en
!== null)
{
C
alert(“Your browser supports Web Storage”);
return;
h
ec
}
alert(“Your browser does not support Web Storage”);
pt
}
</script>
rA
</head>
<body onload=”checkSupport();”>
Fo
</body>
</html>
se
Lasts for the entire duration of the session and hence, is not persistent.
U
tre
Makes use of named key/value pairs which are enclosed within double quotes.
en
Stores the data using the named key, whereas the data is retrieved by referring
to that key.
C
h
Key is a string, whereas the value stored in the key can be of any data type such
ec
as string, boolean, integer, or float. Regardless of the type of data that is stored,
it is actually stored internally as a string.
pt
rA
Storing and retrieving data of other types requires the use of functions to convert
them into the appropriate data types.
Fo
nl
various data types.
O
se
Key Value
U
Name Sarah
tre
book C Programming
en
Email [email protected]
age 28
pt
uservalid true
rA
Fo
nl
follows:
O
Storing and retrieving data - setItem() and getItem() methods are used to store
se
and retrieve data from session storage respectively.
U
Syntax to use setItem() and getItem() methods is as follows:
tre
To assign data
en
sessionStorage.setItem(key, value);
where, C
h
ec
O
var item = sessionStorage.getItem(key);
se
where,
U
item: Is the variable into which the data will be saved.
tre
en
key: Is the named key to refer to the data.
C
h
ec
pt
rA
Fo
y
Code snippet demonstrates how to set and retrieve a name using
nl
sessionStorage object.
O
<!DOCTYPE html>
se
<html>
<head>
U
<title>Working with Session Storage</title>
<script>
tre
function testStorage() {
if ((‘sessionStorage’ in window) && window[‘sessionStorage’] !==
en
null)
{
C
sessionStorage.setItem(‘name’, ‘Sarah’);
alert(‘The name is: ‘ + sessionStorage.getItem(‘name’));
h
}
ec
}
</script>
pt
</head>
rA
O
sessionStorage.removeItem(key);
se
where,
U
key: Is the named key to refer to the data.
tre
en
Clearing data
sessionStorage.clear();
C
h
ec
pt
rA
Fo
se
Data is persistent and can be retrieved when a user visits the site again.
U
tre
Is used, if data needs to be stored for more than a single session.
en
Works in a similar fashion as session storage.
C
h
Uses the same functions, such as setItem(), getItem(), removeItem(), and
ec
clear().
pt
rA
Fo
y
Code snippet demonstrates the use of local storage to store the value of
nl
username field and later, retrieve the value in another Web page.
O
<!DOCTYPE html>
se
<html>
<title> Local Storage </title>
U
<script>
function store() {
tre
if ((‘localStorage’ in window) && window[‘localStorage’] !== null) {
en
var username = document.getElementById(‘username’).value;
localStorage.setItem(‘username’, username);
} else {
C
alert (‘your browser does not support storage’);
h
}
ec
}
function cancel_store() {
pt
localStorage.removeItem(‘username’);
} else {
Fo
y
Code snippet demonstrates the use of local storage to store the value of
nl
username field and later, retrieve the value in another Web page.
O
se
</script>
</head>
U
<body>
<form method=”get” action=”success.html”>
tre
Username: <input type=”text” id=”username” value=”” size=”20”
onblur=”store()”/>
en
<input type=”submit” value=”Submit”/>
<input type=”reset” Value=”Cancel” onclick=”cancel_store()”/>
</body>
</html> C
h
ec
pt
rA
Fo
y
Code snippet shows the success.html page that retrieves value from the local
nl
storage and displays it in the browser.
O
<!DOCTYPE html>
<head>
se
<title> Local Storage </title>
U
<script>
function print() {
tre
var username = localStorage.getItem(‘username’);
document.getElementById(‘lblMsg’).innerHTML = ‘Username: is <b>’+
en
username+’</b>’;
}
</script>
</head> C
h
<body onload=”print()”>
ec
<label id=”lblMsg”></label><br>
pt
</body>
</html>
rA
Fo
se
Databases, such as relational database stores the data in the form of tables.
U
tre
A table comprises rows and columns that are used to store data.
en
The representation of data from a table is in the form of records.
C
h
HTML5 has introduced a new Web Storage API which can host Web databases
ec
O
se
It is basically an object store that can be used to store and manipulate data on
the client-side.
U
The object store is the primary storage mechanism that stores the object in the
tre
database managed locally within the browser.
en
It enables to create an object store of a particular type in which objects can be
persisted using JavaScript.
C
IndexedDB enables to create Web applications with rich query abilities and
h
which can work both online and offline.
ec
pt
The synchronous API can be used with WebWorkers, whereas asynchronous API can
Fo
O
se
Browsers implement the IndexedDB object with their own prefixes. For example,
Chrome browser uses the webkit prefix, whereas Mozilla supports –moz prefix.
U
tre
Following table lists the browser support for the IndexedDB API.
en
Firefox Chrome Safari Opera iOS Safari
IE
6.0 - - C - - 3.2
h
ec
- 12.0moz 19.0webkit - - -
y
nl
Database - The IndexedDB database comprises more than one object store.
O
Each database contains a name that identifies the origin of the database and a
version number which identifies the lifetime of the database.
se
Object Store - Is the main mechanism to store data in a database. They hold
U
the data stored in the database in the form of records.
tre
Keys - Each record stored in the database is identified by a unique key.
en
Values - Are the data stored in the records.
C
h
Key Path - Is a string that defines how the browser should extract key from a
ec
value. The key from a value can be extracted either in the object store or index.
pt
Index - Is used when the data from the object store is retrieved based on some
rA
y
Some of the other basic constructs of IndexedDB API are as follows:
nl
Requests - Operations, such as reading or writing on the database is performed
O
using a request. Each request contain attributes, such as flag, source object,
result, and error.
se
U
Cursor - Is a mechanism used to retrieve multiple records from a database.
tre
Key Range - Records from the object stores and indexes are retrieved using
en
keys or key ranges. A key range refers to retrieval of data between specified
bounds based on the keys.
C
h
ec
pt
rA
Fo
y
Steps to implement the IndexedDB API in a Web application are as follows:
nl
O
Open a database
se
Create an object store
U
Start a transaction
tre
Perform some database operations, such as add and retrieve
en
Work with the retrieved results
C
h
ec
pt
rA
Fo
nl
O
Code snippet shows the code to open a database
se
var indexedDB = window.indexedDB || window.webkitIndexedDB ||
U
window.mozIndexedDB || window.msIndexedDB;
var request = indexedDB.open(“CompanyDB”, 1);
tre
request.onsuccess = function (event) {
. . .
en
};
request.onerror = function (event) {
C
console.log(“IndexedDB error: “ + event.target.errorCode);
};
h
ec
pt
rA
Fo
nl
O
After the database is opened, it can be structured by providing a version number
which helps to set up the database.
se
U
Code snippet shows the code that specifies the version number to the database
tre
var setVrequest = db.setVersion(“1.99”);
setVrequest.onsuccess = function(event) {
en
. . .
}
C
h
ec
pt
rA
Fo
nl
O
Structure of IndexedDB database facilitates the storage of multiple object stores.
se
U
Object store is created using createObjectStore() method which accepts two
arguments namely, the store name and a parameter object.
tre
Code snippet demonstrates the code to create an object store named employee
en
in the CompanyDB database.
var employeeData = [
C
{ name: “John Smith”, email: “[email protected]” },
h
{ name: “Jill Patrick”, email: “[email protected]” },
ec
];
rA
objectStore.put(employeeData[i]);
alert(“Record added”);
} HTML5 Web Storage / Session 18 27
© Aptech Ltd.
y
Creating a Transaction
nl
O
To perform database operation, such as retrieving data from the object store,
IndexedDB provides a IDBTransaction object.
se
U
This object can be created in three mode namely, read-only, read-write, and
snapshot.
tre
Code snippet demonstrates the code to retrieve data from the employee object
en
store using the get() function of the transaction object.
// Handle errors!
rA
};
request.onsuccess = function(event) {
// Do something with the request.result!
Fo
alert(“Name: “ + request.result.name);
};
© Aptech Ltd. HTML5 Web Storage / Session 18 28
y
Opening a Cursor
nl
O
Cursor is used to retrieve multiple records from an object store.
se
U
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.
tre
Code snippet demonstrates the code to retrieve multiple records from the
en
employee object store.
C
store = db.transaction(“employee”).objectStore(“employee”);
h
store.openCursor().onsuccess = function(event) {
ec
cursor.value.name);
cursor.continue();
}
Fo
};
nl
follows:
O
Internationalized sorting deals with sorting of string data. As the database does
se
not follow any international order for storing data, internationalized sorting is not
supported by the API.
U
tre
IndexedDB API does not synchronize client-side database with the server-side
databases.
en
C
IndexedDB API supports querying the client-side database, but does not support
the use of operators, such as LIKE that is used by Structured Query Language
h
(SQL).
ec
pt
rA
Fo
se
U
A native app, when compared with Web app is installed on a device and has a
faster response, because it has a direct user interface.
tre
en
BlackBerry Messenger (BBM) is a native app available on blackberry mobile
devices.
C
h
ec
pt
rA
Fo
O
se
Web apps have the ability of offline access which means that the user need not
have a network connection.
U
Following table lists differences between the native apps and HTML5 apps.
tre
en
Native Apps HTML5 Apps
C
Native Apps runs on iOS and Android devices that
can be downloaded or purchased from the online
HTML5 Apps runs on a Web server, usually in a
Web browser.
h
app stores.
ec
Native Apps use programming language, such as Web developers use HTML, JavaScript, and CSS.
pt
Java for Android devices and Objective C for iOS They need to acquire the skills of Java and
rA
y
Main advantage of using HTML5 is to create applications that executes on a wide
nl
range of devices easily. Some of the reasons to develop HTML5 applications are as
O
follows:
Users cannot identify the differences - Cannot identify whether they are
se
working on a hybrid HTML5-native application or a fully native application or an
HTML5 application.
U
Users adjust styles for devices - HTML5 apps can be viewed on any devices
tre
that contains Web browser.
en
Upcoming functionalities - HTML5 does not support all features on a device,
but it is coming up with new functionalities.
C
h
Improving Performance - Many developers learn new methods to improve the
ec
performance of Web.
pt
Developers are not locked in app stores - HTML5 developers are not
restricted to an app store. Instead, they can create applications and sell them
like any other Web page.
© Aptech Ltd. HTML5 Web Storage / Session 18 33
y
Major advantage of native apps over HTML5 apps is that they are faster than
nl
HTML5 apps. Native apps provide more benefits over HTML5 apps. These are as
O
follows :
se
Providing access to device hardware - There are no APIs available for
accelerometers, cameras, or any other device hardware for HTML5 apps.
U
Uploading Files - Native apps can access the file system in Android and some
tre
files in iOS. However, the HTML5 file API does not work on Android or iOS.
en
Push Notifications - The push notifications are sent always with an open IP
connection to applications on the iOS device.
C
h
Accessing device files - Native apps communicate with files on devices, such
ec
as contacts and photos. However, these files cannot be seen from HTML5 app.
pt
Superior graphics than HTML5 - HTML5 has a canvas element, but it will not
rA
y
Users have a choice of developing their application in HTML5 and convert them
nl
into a native app
O
Users can use some tools to convert an HTML5 app to Native app and they are as
follows:
se
U
tre
PhoneGap - Is an HTML5 app that allows the user to create native apps with
Web technologies and is accessible to app stores and APIs.
en
C
Appcelerator - Is a cross-platform mobile application development support and
allows the users to create Android, iOS, and mobile Web apps.
h
ec
pt
rA
Fo
y
Web Storage is a W3C specification that provides functionality for storing data
nl
on the client-side for both temporary as well as permanent needs.
O
HTML5 Web applications make use of Web storage to implement client-side
se
persistent storage and they are: session storage and local storage.
U
Session storage keeps track of data specific to one window or tab.
tre
The setItem() and getItem() methods are used to store and retrieve the data
en
from session storage.
C
Local storage enables to save data for longer periods on the user’s computer,
h
through the browser.
ec
pt
IndexedDB API is basically an object store that can be used to store and
manipulate data on the client-side.
rA