localStorage.setItem("name", "Chris");Client-side storage / notebook
Client-side storage
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
let myName = localStorage.getItem("name");
myName; localStorage.removeItem("name");
myName = localStorage.getItem("name");
myName; localStorage.setItem("name", "Chris");
let myName = localStorage.getItem("name");
myName; let myName = localStorage.getItem("name");
myName; // create needed constants
const rememberDiv = document.querySelector(".remember");
const forgetDiv = document.querySelector(".forget");
const form = document.querySelector("form");
const nameInput = document.querySelector("#entername");
const submitBtn = document.querySelector("#submitname");
const forgetBtn = document.querySelector("#forgetname");
const h1 = document.querySelector("h1");
const personalGreeting = document.querySelector(".personal-greeting"); // Stop the form from submitting when a button is pressed
form.addEventListener("submit", (e) => e.preventDefault()); // run function when the 'Say hello' button is clicked
submitBtn.addEventListener("click", () => {
// store the entered name in web storage
localStorage.setItem("name", nameInput.value);
// run nameDisplayCheck() to sort out displaying the personalized greetings and updating the form display
nameDisplayCheck();
}); // run function when the 'Forget' button is clicked
forgetBtn.addEventListener("click", () => {
// Remove the stored name from web storage
localStorage.removeItem("name");
// run nameDisplayCheck() to sort out displaying the generic greeting again and updating the form display
nameDisplayCheck();
}); // define the nameDisplayCheck() function
function nameDisplayCheck() {
// check whether the 'name' data item is stored in web Storage
if (localStorage.getItem("name")) {
// If it is, display personalized greeting
const name = localStorage.getItem("name");
h1.textContent = `Welcome, ${name}`;
personalGreeting.textContent = `Welcome to our website, ${name}! We hope you have fun while you are here.`;
// hide the 'remember' part of the form and show the 'forget' part
forgetDiv.style.display = "block";
rememberDiv.style.display = "none";
} else {
// if not, display generic greeting
h1.textContent = "Welcome to our website ";
personalGreeting.textContent =
"Welcome to our website. We hope you have fun while you are here.";
// hide the 'forget' part of the form and show the 'remember' part
forgetDiv.style.display = "none";
rememberDiv.style.display = "block";
}
} nameDisplayCheck(); // Create an instance of a db object for us to store the open database in
let db; // Open our database; it is created if it doesn't already exist
// (see the upgradeneeded handler below)
const openRequest = window.indexedDB.open("notes_db", 1); // error handler signifies that the database didn't open successfully
openRequest.addEventListener("error", () =>
console.error("Database failed to open"),
);
// success handler signifies that the database opened successfully
openRequest.addEventListener("success", () => {
console.log("Database opened successfully");
// Store the opened database object in the db variable. This is used a lot below
db = openRequest.result;
// Run the displayData() function to display the notes already in the IDB
displayData();
}); // Set up the database tables if this has not already been done
openRequest.addEventListener("upgradeneeded", (e) => {
// Grab a reference to the opened database
db = e.target.result;
// Create an objectStore in our database to store notes and an auto-incrementing key
// An objectStore is similar to a 'table' in a relational database
const objectStore = db.createObjectStore("notes_os", {
keyPath: "id",
autoIncrement: true,
});
// Define what data items the objectStore will contain
objectStore.createIndex("title", "title", { unique: false });
objectStore.createIndex("body", "body", { unique: false });
console.log("Database setup complete");
});// Create a submit event handler so that when the form is submitted the addData() function is run
form.addEventListener("submit", addData);// Define the addData() function
function addData(e) {
// prevent default - we don't want the form to submit in the conventional way
e.preventDefault();
// grab the values entered into the form fields and store them in an object ready for being inserted into the DB
const newItem = { title: titleInput.value, body: bodyInput.value };
// open a read/write db transaction, ready for adding the data
const transaction = db.transaction(["notes_os"], "readwrite");
// call an object store that's already been added to the database
const objectStore = transaction.objectStore("notes_os");
// Make a request to add our newItem object to the object store
const addRequest = objectStore.add(newItem);
addRequest.addEventListener("success", () => {
// Clear the form, ready for adding the next entry
titleInput.value = "";
bodyInput.value = "";
});
// Report on the success of the transaction completing, when everything is done
transaction.addEventListener("complete", () => {
console.log("Transaction completed: database modification finished.");
// update the display of data to show the newly added item, by running displayData() again.
displayData();
});
transaction.addEventListener("error", () =>
console.log("Transaction not opened due to error"),
);
}// Define the displayData() function
function displayData() {
// Here we empty the contents of the list element each time the display is updated
// If you didn't do this, you'd get duplicates listed each time a new note is added
while (list.firstChild) {
list.removeChild(list.firstChild);
}
// Open our object store and then get a cursor - which iterates through all the
// different data items in the store
const objectStore = db.transaction("notes_os").objectStore("notes_os");
objectStore.openCursor().addEventListener("success", (e) => {
// Get a reference to the cursor
const cursor = e.target.result;
// If there is still another data item to iterate through, keep running this code
if (cursor) {
// Create a list item, h3, and p to put each data item inside when displaying it
// structure the HTML fragment, and append it inside the list
const listItem = document.createElement("li");
const h3 = document.createElement("h3");
const para = document.createElement("p");
listItem.appendChild(h3);
listItem.appendChild(para);
list.appendChild(listItem);
// Put the data from the cursor inside the h3 and para
h3.textContent = cursor.value.title;
para.textContent = cursor.value.body;
// Store the ID of the data item inside an attribute on the listItem, so we know
// which item it corresponds to. This will be useful later when we want to delete items
listItem.setAttribute("data-note-id", cursor.value.id);
// Create a button and place it inside each listItem
const deleteBtn = document.createElement("button");
listItem.appendChild(deleteBtn);
deleteBtn.textContent = "Delete";
// Set an event handler so that when the button is clicked, the deleteItem()
// function is run
deleteBtn.addEventListener("click", deleteItem);
// Iterate to the next item in the cursor
cursor.continue();
} else {
// Again, if list item is empty, display a 'No notes stored' message
if (!list.firstChild) {
const listItem = document.createElement("li");
listItem.textContent = "No notes stored.";
list.appendChild(listItem);
}
// if there are no more cursor items to iterate through, say so
console.log("Notes all displayed");
}
});
}// Define the deleteItem() function
function deleteItem(e) {
// retrieve the name of the task we want to delete. We need
// to convert it to a number before trying to use it with IDB; IDB key
// values are type-sensitive.
const noteId = Number(e.target.parentNode.getAttribute("data-note-id"));
// open a database transaction and delete the task, finding it using the id we retrieved above
const transaction = db.transaction(["notes_os"], "readwrite");
const objectStore = transaction.objectStore("notes_os");
const deleteRequest = objectStore.delete(noteId);
// report that the data item has been deleted
transaction.addEventListener("complete", () => {
// delete the parent of the button
// which is the list item, so it is no longer displayed
e.target.parentNode.parentNode.removeChild(e.target.parentNode);
console.log(`Note ${noteId} deleted.`);
// Again, if list item is empty, display a 'No notes stored' message
if (!list.firstChild) {
const listItem = document.createElement("li");
listItem.textContent = "No notes stored.";
list.appendChild(listItem);
}
});
} const videos = [
{ name: "crystal" },
{ name: "elf" },
{ name: "frog" },
{ name: "monster" },
{ name: "pig" },
{ name: "rabbit" },
]; function init() {
// Loop through the video names one by one
for (const video of videos) {
// Open transaction, get object store, and get() each video by name
const objectStore = db.transaction("videos_os").objectStore("videos_os");
const request = objectStore.get(video.name);
request.addEventListener("success", () => {
// If the result exists in the database (is not undefined)
if (request.result) {
// Grab the videos from IDB and display them using displayVideo()
console.log("taking videos from IDB");
displayVideo(
request.result.mp4,
request.result.webm,
request.result.name,
);
} else {
// Fetch the videos from the network
fetchVideoFromNetwork(video);
}
});
}
} // Fetch the MP4 and WebM versions of the video using the fetch() function,
// then expose their response bodies as blobs
const mp4Blob = fetch(`videos/${video.name}.mp4`).then((response) =>
response.blob(),
);
const webmBlob = fetch(`videos/${video.name}.webm`).then((response) =>
response.blob(),
);
// Only run the next code when both promises have fulfilled
Promise.all([mp4Blob, webmBlob]).then((values) => {
// display the video fetched from the network with displayVideo()
displayVideo(values[0], values[1], video.name);
// store it in the IDB using storeVideo()
storeVideo(values[0], values[1], video.name);
}); // Define the storeVideo() function
function storeVideo(mp4, webm, name) {
// Open transaction, get object store; make it a readwrite so we can write to the IDB
const objectStore = db
.transaction(["videos_os"], "readwrite")
.objectStore("videos_os");
// Add the record to the IDB using add()
const request = objectStore.add({ mp4, webm, name });
request.addEventListener("success", () =>
console.log("Record addition attempt finished"),
);
request.addEventListener("error", () => console.error(request.error));
} // Define the displayVideo() function
function displayVideo(mp4Blob, webmBlob, title) {
// Create object URLs out of the blobs
const mp4URL = URL.createObjectURL(mp4Blob);
const webmURL = URL.createObjectURL(webmBlob);
// Create DOM elements to embed video in the page
const article = document.createElement("article");
const h2 = document.createElement("h2");
h2.textContent = title;
const video = document.createElement("video");
video.controls = true;
const source1 = document.createElement("source");
source1.src = mp4URL;
source1.type = "video/mp4";
const source2 = document.createElement("source");
source2.src = webmURL;
source2.type = "video/webm";
// Embed DOM elements into page
section.appendChild(article);
article.appendChild(h2);
article.appendChild(video);
video.appendChild(source1);
video.appendChild(source2);
}// Register service worker to control making site work offline
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register(
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/sw.js",
)
.then(() => console.log("Service Worker Registered"));
}self.addEventListener("install", (e) => {
e.waitUntil(
caches
.open("video-store")
.then((cache) =>
cache.addAll([
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/",
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/index.html",
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/index.js",
"/learning-area/javascript/apis/client-side-storage/cache-sw/video-store-offline/style.css",
]),
),
);
});self.addEventListener("fetch", (e) => {
console.log(e.request.url);
e.respondWith(
caches.match(e.request).then((response) => response || fetch(e.request)),
);
});