localStorage & sessionStorage
localStorage.setItem("myKey", "myValue");
// or
localStorage.myKey = "myValue";
var data = localStorage.getItem("myKey");
// or
var data = localStorage.myKey;
localStorage.removeItem("myKey");
// or
delete localStorage.myKey;
localStorage.clear();
var length = localStorage.length;
Session Storage | Local Storage |
---|---|
Survives page refresh |
Survives browser close |
Short life span |
Longer life span |
|
|
Stored client side. User can clear data. |
|
Synchronous API. Blocks UI. |
var request = window.indexedDB.open("MyDatabase");
request.onerror = function(event) {
console.log("failure");
};
request.onsuccess = function(event) {
console.log("success");
// now we can access the database
};
var transaction = db.transaction(["customers"]);
var objectStore = transaction.objectStore("customers");
var request = objectStore.get("444-44-4444");
request.onerror = function(event) {
// Handle errors!
};
request.onsuccess = function(event) {
// Do something with the request.result!
alert("Name for SSN 444-44-4444 is " + request.result.name);
};
<html manifest="example.appcache">
...
CACHE MANIFEST
# v1 - 2014-12-09
# This is a comment.
http://www.example.com/index.html
http://www.example.com/header.png
http://www.example.com/blah/blah
if (navigator.onLine) {
// YAAAY, we have network!
}
window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOnlineStatus);
var myWorker = new Worker("my_task.js");
myWorker.addEventListener("message", function (oEvent) {
console.log("Called back by the worker!\n");
}, false);
myWorker.postMessage(""); // start the worker.
window.addEventListener("deviceorientation", handleOrientation, true);
function handleOrientation(event) {
var absolute = event.absolute;
var alpha = event.alpha;
var beta = event.beta;
var gamma = event.gamma;
// Do stuff with the new orientation data
}
// find user position
navigator.geolocation.getCurrentPosition(function(position) {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
});
// watch user position, update as user moves
var watchID = navigator.geolocation.watchPosition(function(position) {
do_something(position.coords.latitude, position.coords.longitude);
});
ws
protocol
// Create connection
var mysocket = new WebSocket("ws://example.com/socketserver");
// Send data when connection has opened
mysocket.onopen = function () {
mysocket.send("Hello, World!");
}
// Receive data from server
mysocket.onmessage = function (event) {
console.log(event.data);
}
getUserMedia
to grab video/audio
// Cross-browser
navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia ||
navigator.webkitGetUserMedia;
navigator.getUserMedia({
video: true,
audio: true
}, function (localstream) {
var vid = document.querySelector("video");
vid.src = URL.createObjectURL(localstream);
vid.play();
}, function (error) {
console.log("Error occured in getUserMedia", error);
});