Exercises
Objectives
This chapter introduces no new concepts. It’s a chance to practice everything from this module: storage, cookies, and the permission-based browser APIs.
Exercises 1-6 run in this course’s tooling exactly like earlier modules. Exercises 7-10 use APIs that need a real browser (the same verification limitation covered in each lesson), write the code and reason through what it should do.
Exercises
-
Save the string
"purple"under the key"color"usinglocalStorage. Read it back and log it. Check:purple. -
Save an object
{ volume: 80, muted: false }under the key"prefs"usingJSON.stringify(). Read it back withJSON.parse()and log the parsed object. Check:{ volume: 80, muted: false }. -
Save the string
"unsaved text"under the key"formDraft"usingsessionStorageinstead oflocalStorage. Read it back and log it. Check:unsaved text. -
Save two keys with
localStorage, then use.removeItem()on just one of them. Confirm the removed key’s.getItem()returnsnull, and the other key is unaffected. -
Set two cookies,
"consent=true"and"region=us". Logdocument.cookieand confirm both appear, separated by;. -
Delete the
"region"cookie from the previous exercise by setting itsexpiresto a date in the past. Confirm it no longer appears indocument.cookie, while"consent"still does. -
Write the code to request the user’s location with
getCurrentPosition(), logging the latitude and longitude on success, and a specific message for each of the three possibleerror.codevalues on failure. -
Write a click handler that copies a string to the clipboard with
navigator.clipboard.writeText(), wrapped intry/catch. Explain, in your own words, why this code would fail if it ran automatically on page load instead of inside a click handler. -
Write the code to request notification permission, and, if granted, show a notification with a title and a
body. Add an.onclickhandler that logs a message and callswindow.focus(). -
Write a
worker.jsthat receives an array throughself.onmessage, adds up its numbers, and sends the total back. Write the matchingmain.jsthat creates the worker, sends it[1, 2, 3, 4, 5], and logs the result. Explain, in your own words, why this workload would be a reasonable one to hand off to a worker instead of running directly on the main thread.
Recap
You can now save data that persists with localStorage, save data scoped to a tab with sessionStorage, read and write cookies, and describe how to request a user’s location, use the clipboard, show notifications, offload heavy work to a worker, and draw with canvas. That’s the full tour of the browser features beyond the DOM and events.
Next lesson: this module’s mini project, a drawing board combining canvas, mouse events, and storage into one working page.