HTML5 brought to us the possibility to work offline without very complex solutions. We can make websites and webapps which can work 100% offline with few effort.

There are many components and many ways to make our webapps able to work without internet connection. To store data and make it available offline, we can basically use:

HTML5 Offline Technologies

  • Web Storage simply provides a key-value mapping, e.g. localStorage["name"] = username;. Unfortunately, present implementations only support string-to-string mappings, so you need to serialise and de-serialise other data structures. You can do so using JSON.stringify() and JSON.parse().
  • Web SQL Database gives you all the power – and effort – of a structured SQL relational database.
  • Indexed Database is somewhere in between Web Storage and Web SQL Database. Like Web Storage, it’s a straightforward key-value mapping, but it supports indexes like those of relational databases, so searching objects matching a particular field is fast; you don’t have to manually iterate through every object in the store.
  • File Access is an API for reading file content in JavaScript. Given a set of files the user has added to a “file” input element, you can read the content of the file or reference it as a URL, e.g. if the user has specified an image file, you can show the image. There are also proposals underway for file writing capabilities.

In the SAPUI5 framework we have a component which manipulates the HTML5 Web Storage object. This component is jQuery.sap.storage and is this one that I’m going to show you how to use.

Why this one?

  • It’s simple to understand and to use;
  • It’s the only one which can be manipulated straight with SAPUI5;
  • It’s supported for all modern browsers;
  • It’s perfect to use with JSONModel, you can store all your Model in one entry.

Check the API for jQuery.sap.storage here:

https://sapui5.netweaver.ondemand.com/sdk/#docs/api/symbols/jQuery.sap.storage.html

I won’t explain the HTML5 Web Storage object in details, for further information go through the links below:

http://www.w3schools.com/html/html5_webstorage.asp

http://www.html5rocks.com/en/features/storage

For now, we just need to know that the limit for Web Storage is 5 MB, data is stored as string in name/value pairs and there are two types of Storage:

  • Local Storage – stores data with no expiration date, you can close the browser and data still there (jQuery.sap.storage.Type.local in UI5);
  • Session Storage – stores data for one session, if you close the browser (or tab) data is lost (jQuery.sap.storage.Type.session in UI5).

These are the main methods for Web Storage in UI5.


//Get Storage object to use
oStorage = jQuery.sap.storage(jQuery.sap.storage.Type.local);
//Get data from Storage
oStorage.get("myLocalData");
//Set data into Storage
oStorage.put("myLocalData", oData);
//Clear Storage
oStorage.clear();

Here you can check an application using jQuery.sap.storage.

https://077e7aad3963c58ca664a8cd5b57ce370a73b848.googledrive.com/host/0B2gJUv6a_V1dUTZtYVFTTDZsbXM/storage.html


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="UTF-8">
<meta name=viewport content="width=device-width, initial-scale=1">
<meta name="author" content="Mauricio Lauffer">
<title>Storage Test</title>
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js" id="sap-ui-bootstrap"
  data-sap-ui-libs="sap.m" data-sap-ui-theme="sap_bluecrystal">
</script>
<script type="text/javascript">
  var data = {
  "Collection" : [ {
  "id" : "1"
  } ]
  };
  //Create Model
  var oModel = new sap.ui.model.json.JSONModel();
  oModel.setData(data);
  //Storage
  jQuery.sap.require("jquery.sap.storage");
  oStorage = jQuery.sap.storage(jQuery.sap.storage.Type.local);
  //Check if there is data into the Storage
  if (oStorage.get("myLocalData")) {
  console.log("Data is from Storage!");
  var oData = oStorage.get("myLocalData");
  oModel.setData(oData);
  }
  //Create Elements
  var oList = new sap.m.List("localStorage");
  var oBtn1 = new sap.m.Button({
  icon : "sap-icon://add",
  text : "Add to Model and Storage",
  press : function() {
  var oNew = {
  id : $.now()
  };
  var oData = oModel.getData();
  oData.Collection.push(oNew);
  oModel.refresh(true);
  oStorage.put("myLocalData", oData);
  }
  });
  var oBtn2 = new sap.m.Button({
  icon : "sap-icon://delete",
  text : "Clear Storage",
  press : function() {
  oStorage.clear();
  }
  });
  var oPage = new sap.m.Page("page1", {
  title : "Storage Test",
  content : [ oList ],
  subHeader : new sap.m.Bar({
  contentRight : [ oBtn1, oBtn2 ]
  })
  });
  //Create Application
  var oApp = new sap.m.App("myApp");
  oApp.setModel(oModel);
  oApp.addPage(oPage);
  oApp.placeAt("content");
  //Binding
  oList.bindItems("/Collection", new sap.m.StandardListItem({
  title : "{id}",
  description : "Local Storage"
  }));
</script>
</head>
<body class="sapUiBody" role="application">
  <div id="content"></div>
</body>
</html>


When you access the app for the first time there is nothing into Local Storage area and it’s shown just one item on screen.

This item come from a variable (var data) defined in the app.

/wp-content/uploads/2014/06/sto1_486040.png

After to press the “Add” button, we have one more item on screen and now we have our first entry into Local Storage Area.

You can check it out on JavaScript’s console.

/wp-content/uploads/2014/06/sto2_486080.png

After have pressed the “Add” button more few times, I refreshed the page (CTRL+F5) and the Model was filled with data from the previous Local Storage entry.

Check the message “Data is from Storage” on JavaScript’s console.

/wp-content/uploads/2014/06/sto5_486081.png

You can do more, a lot more. This is just the first step with offline data in UI5 apps.

How I said at the beginning, you can use many others approaches to make your data offline.
For a full offline experience, you should use Appcache. It isn’t a SAPUI5 component, it’s an HTML5 object.

There are few blogs about it here and lots of pages out there. You can check the links below.

http://www.w3schools.com/html/html5_app_cache.asp

http://www.html5rocks.com/en/tutorials/appcache/beginner/

To report this post you need to login first.

14 Comments

You must be Logged on to comment or reply to a post.

  1. Marcos Andrade

    Hello Mauricio,


    excellent post and very useful. I have seen some other blogs that used Indexed Database. I haven`t gotten into detail about the options but which approach you think suits more to hold data offline in SAPUI5?

    thanks in advance.

    Marcos

    (0) 
    1. Mauricio Lauffer Post author

      Hi Marcos.

      Thanks for asking.

      IndexedDB has better performance, but it isn’t supported by all browsers yet.

      jQuery.sap.storage uses an HTML5 feature called Web Storage. The performance isn’t good for large databases, but it’s ok for small ones and it has good support by all modern browsers.

      So, I’d say if you’re looking for performance using large databases, go for IndexedDB.

      I haven’t needed to use IndexedDB until now  😉

      You can check these links to see browser’s support.

      http://caniuse.com/#feat=indexeddb

      http://caniuse.com/#feat=namevalue-storage

      (0) 
      1. Marcos Andrade

        Hello Mauricio,

        thank you for the explanation. We have some plans to develop an application for performance management in the near future and it is good to know that UI5 enables us to have offline features. I will dig into that.

        thanks again.

        Kind Regards

        (0) 
  2. Ravi kiran R

    Hi Mauricio,

    Very nice and usefull blog.

    Just thought of asking this, since we store in local storage how secured is the data, do we some how have the chance of securing the data ??

    Thanks,

    Ravikiran

    (0) 
  3. Karthik A

    Hi Ravi,

    Correct me if I am wrong.

    Local dB has only 5 MB of disk space to store our data.

    If I want to store Images and files here..At that time this entire application will crashed rite?

    Thanks,

    Karthik A

    (0) 
    1. Ravi kiran R

      Hi Karthik,

      I have tried storing values on local storage as well as on session storage. But i have not tried of storing images locally. Yeah may be when  the size exceeds, there might be performance issue.

      Thanks Mauricio Lauffer for the link

      Regards,

      Ravikiran

      (0) 
  4. Arthur Silva

    Hello Mauricio,


    I have a requirement which consists to store some offline data in a android mobile application(*.apk). When the phone finally reach a wi-fi signal, the data stored on phone will be sync through the button “sync now” on the mobile’s first screen. In overall, the data need to be stored on phone’s memory because there is no connection to internet during execution time, the data will be sync when the employees arrive back to the office.

    My question is, does this solutions works on android application(apk), or do I need to explore Kapsel offline odata?

    Arthur Silva

    (0) 
  5. Devisha Bhavik

    Hi,

    Nice blog to get started in this direction.

    I have tried above code and it worked fine in chrome when I closed the browser and opened it again.

    But, is it just local to the browser I am using or local to the machine?

    I have tried it in IE and I did not see the data entered through chrome. Also, when I opened incognito chrome window, I did not see the data as well.

    Also, if we clear the cache on the browser, will these data get deleted?

    If device/machine gets restarted, will it keep the data?

    -Bhavik

    (0) 
    1. Mauricio Lauffer Post author

      It’s local to the browser. You don’t share cache between browsers and you don’t share local storage as well.

      You can reset the device without problems, data’ll be kept.

      Clearing cache has no effect on your local storage data, but if you delete the cookies your data will be deleted.

       

       

      Sorry for the super late response…

      (0) 

Leave a Reply