CodingNic

Browser APIs

Exercises

Browser APIs 35 min read

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

  1. Save the string "purple" under the key "color" using localStorage. Read it back and log it. Check: purple.

  2. Save an object { volume: 80, muted: false } under the key "prefs" using JSON.stringify(). Read it back with JSON.parse() and log the parsed object. Check: { volume: 80, muted: false }.

  3. Save the string "unsaved text" under the key "formDraft" using sessionStorage instead of localStorage. Read it back and log it. Check: unsaved text.

  4. Save two keys with localStorage, then use .removeItem() on just one of them. Confirm the removed key’s .getItem() returns null, and the other key is unaffected.

  5. Set two cookies, "consent=true" and "region=us". Log document.cookie and confirm both appear, separated by ; .

  6. Delete the "region" cookie from the previous exercise by setting its expires to a date in the past. Confirm it no longer appears in document.cookie, while "consent" still does.

  7. 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 possible error.code values on failure.

  8. Write a click handler that copies a string to the clipboard with navigator.clipboard.writeText(), wrapped in try/catch. Explain, in your own words, why this code would fail if it ran automatically on page load instead of inside a click handler.

  9. Write the code to request notification permission, and, if granted, show a notification with a title and a body. Add an .onclick handler that logs a message and calls window.focus().

  10. Write a worker.js that receives an array through self.onmessage, adds up its numbers, and sends the total back. Write the matching main.js that 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.