Lecture Presentation

Content

  • Offline Capabilities
  • Web Storage
  • JSON
  • Network Requests
  • Web APIs

Offline Capabilities

  • Network connection required as a default to start mobile web app
  • HTML5 Offline Applications
    • HTML5 introduces offline capabilities where a network connection is not required the second time a web application is started (a web address is visited in the browser).
  • Easy to turn on
    • Getting an app to start offline in the browser is easy. Getting it to work with server side storage etc once the app is online again is a lot harder (syncing issues), even though there are libraries to help.

Offline Manifest

  • Procedure to get a web app to work offline
  • Specify a manifest file name in html element
    <html manifest="myfile.manifest">
  • Ensure that web server is sending correct mime type
    • This is necessary for the browser to recognize and use the file. The mime type sent in the reponse from the server must be "text/cache-manifest". Set in web server software or via adding your own header in server side script.
  • Create the file with information about what to cache locally
    CACHE MANIFEST
    index.html
    style.css
    logic.js
    https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
    

Storing a value persistantly

  • By persisting a value, we expect it to be around when the page is reloaded or visited on another occation
    • A global JavaScript variable will not do. It will lose its value on reload.
  • Options for persistance
    • Cookies
    • HTML5 Web Storage
    • HTML5 Web Sql Database
    • Server side storage
  • We'll focus on Web Storage in the course

HTML5 Web Storage

  • An API for storing strings persistantly in the browser
    • The browser is responsible for storing the data somewhere, probably in a local file
  • Every stored string has a key (also a string) that uniquely identifies that particular value
  • Store a value
    window.localStorage.setItem("key-name", "Mike");
  • Read a previously stored value
    alert(window.localStorage.getItem("key-name"));
  • Keys for which a value has never been stored has the value null
    if (window.localStorage.getItem("key-name")==null) alert("No value stored!");

HTML5 Web Storage limitations

  • Desktop browsers might ask user for confirmation before storing a value
    • Interestingly enough, mobile browsers stores it immediately without asking the user for permission. Better user experience, but if the reason for asking is security, then perhaps mobile browsers should ask too.
  • Most browsers has a limit of 5 MB per web site for web storage
    • More than that can be approved by the browser asking the user if it is ok to extend storage (don't depend on this since it is browser specific).
  • Can only store strings
    • The JSON format will help in storing complex data like arrays and objects with properties.

JSON - JavaScript Object Notation

  • A data format that is part of JavaScript
    • Today it is just as commonly used, if not more, as XML for specifying complex data in a text format. Not just for JavaScript nowadays.
  • Creating JSON
    • Creating JSON is relatively easy once you know the format. Any programming language that can concatenate a string will be able to create JSON data, but for complex objects a helper/API/library is useful.
  • Parsing JSON
    • Parsing JSON, that is converting from a JSON data string into real values, arrays, objects etc is more work and will need an API or library in your language of choice. JavaScript has it built in, in modern browsers.

JavaScript Objects

  • Short introduction to JavaScript objects
  • Can be created with new Object or a literal using { and }
  • Properties of an object are created as you use them - no declaration necessary
    var person = new Object();
    person.name = "Bob";
    alert("Yes, the name is " + person.name + " without any problem!");
    var someone_else = {};
    someone_else.name = "Jane";
    someone_else.age = 45;
    

JavaScript Arrays

  • Arrays are zero, one or more objects/values in a single variable
    • Dynamic code that is prepared to handle any number of persons/objects etc is a lot easier to write using arrays.
  • Can be created with new Array or literal using [ and ]
  • Number of objects in the array is contained in length property
  • Reference a particular item with the index operator []
  • Add items to an array with push
  • Delete items from an array with splice
  • Example
    var many = new Array();
    many.push(5);
    many.push(10);
    many.push(20);
    for (var i = 0; i < many.length; i++) {
      alert(many[i]);
    }
    many.splice(1, 1); // Remove the middle value (10) in the three value array
    

Using JSON with JavaScript

  • Defining a JavaScript object using JSON in the code
    var obj = { name: "John", born: 1983 };
    alert("My name is " + obj.name);
    obj.born = 1984; // Fix wrong birth year
    var arr = [5, 88, "Carl", 7, { name: "Judy", born: 1990 }];
    
  • Creating JSON from a complex object
    var jstring = JSON.stringify(obj);
  • Parsing JSON into an object
    var obj = JSON.parse(jstring);
  • Parsed JSON requires property names (keys) to be in quotes!
    { "name": "John", "born": 1983 }
    
  • Now you can store any JavaScript object/variable in Web Storage!

Using JSON in separate files

  • Store data in separate file for better organization
    • Storing in separate file can also easily be changed to a server side script that dynamically returns information from a database (but we try to avoid server side script in the course).
  • Include with script element
    • Requires that the file also contains valid JavaScript syntax for setting a variable. That variable with then be available from other JavaScript code in the same page.
  • Include with Ajax
    • Use JavaScript to send an http request to the server without reloading/changing the page.

Include JSON with script element

  • Create a script element to your JSON file in the HTML
    <script src="my-data-variable.json"></script>
  • Declare a variable and define the data in the my-data-variable.json file
    var dataArray = [
      { name: John, born: 1957 },
      { name: Alice, born: 1977 }
    ];
    
  • Anywhere after the script element, the variable is accessible from your own JavaScript
    alert("Received " + dataArray.length + " persons in data array!");

Network Requests from JavaScript

  • AJAX - Asynchronous JavaScript And Xml
    • However, nowadays it's seldom xml so maybe AJAJ would be more appropriate.
  • Fetch data or html without reloading this page or loading some other page
  • Positives
    • Smoother user experience since the AJAX request is invisible to the user
    • More efficient since only changed/added part of a page needs to be downloaded
    • Better separation of html/design and the data of the application
  • Negatives (difficulties)
    • No default user interface to inform the user that we're waiting for something
    • No default history (back/forward) handling when page changes

Performing a network request with JavaScript

  • Use a library like jQuery to hide browser differences and create cleaner code
  • But let's look at the core functionality without a library
    var http = new XMLHttpRequest();
    http.open("GET", "/mydata.json");
    http.onreadystatechange = function() {
      if (http.readyState==4 && http.status==200) {
        alert("Yay, I got som data here " + http.responseText);
      }
    };
    http.send();
    
  • onreadystatechange can fire multiple times to report progress, wait for readyState==4 to be sure all data has arrived
  • Ensure that the http.status code is 200 which means everything was ok without any server side errors
  • Noet that nothing is requested over the wire until send is called

jQuery

  • The most spread JavaScript library in the world
  • Usage - just include with script element
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    
  • Network request with jQuery
    $.ajax({
      url: "/mydata.json",
      dataType: "json",
      success: function(result) {
        alert("Yay, I got som data here " + result);
      },
      error: function(message) {
        alert("Oops! Something went wrong. "+message);
      }
    });
    

Cross Domain Requests (XDR)

  • Blocked by all browsers for security reasons
    • JavaScript on one domain (site) may not make http requests to other domains (sites). If user is logged in at those sites, like Facebook, any site would be able to retrieve a lot of sensitive data (and change it!).
  • Solutions
    • Other site supports JSONP for allowing simpler requests (no posting possible)
    • Other site supports CORS for non-sensitive data and/or known sites
    • Create server side script in your own site to proxy the data (no login/cookies)
    • Enclose your web application in PhoneGap (or similar solution)

JSONP - JSON with Padding

  • Wrap (pad) the response in a JavaScript function call
    • This means that you if you insert a script element with the src attribute set to the network request you'd like to make, you can provide the function to call and thereby intercept and receive the data. A standard of specifying the function name as the callback query string parameter has evolved.
  • Example
    var scriptElement = document.createElement("script");
    scriptElement.src = "http://someothersite.com/my-data.json?callback=yay";
    document.body.appendChild(scriptElement);
    function yay(result) {
      alert("Yay, I got some data here " + result);
    }
    
  • Problems
    • No errors can be detected, like site down or http error response
    • Can't send POST or other requests (only GET works)

Web APIs

  • To successfully build custom applications using data from other services, you need an API
  • Many well known web sites/services has APIs
  • Access usually requires registering and getting an Application ID of some sort
  • The service can use the AppID to limit your usage, or stop you from using the service
  • The AppID should only be used in server side scripts, otherwise it is public knowledge and anyone can use your ID
  • Many sites also require a user to be authenticated to the site, like being logged in to Facebook