1. 浏览器 API

在现代 Web 开发中,浏览器为开发者提供了丰富的 API,用于处理各种任务,如网络请求、剪贴板操作等。本节将介绍一些常用的浏览器 API,并演示其使用方法。

常用浏览器 API 介绍

Fetch API

Fetch API 用于执行网络请求,替代了老旧的 XMLHttpRequest。它的语法更简洁,支持 Promise,使异步代码更具可读性。

示例代码:

  1. // Fetch API 示例
  2. fetch("https://api.example.com/data")
  3. .then((response) => {
  4. if (!response.ok) {
  5. throw new Error("Network response was not ok " + response.statusText);
  6. }
  7. return response.json();
  8. })
  9. .then((data) => {
  10. console.log(data);
  11. })
  12. .catch((error) => {
  13. console.error("There was a problem with the fetch operation:", error);
  14. });

操作剪贴板 API

剪贴板 API 允许 Web 应用程序读取或写入剪贴板内容,极大地提高了用户体验。例如,用户可以点击按钮将文本复制到剪贴板。

示例代码:

  1. // 复制文本到剪贴板
  2. function copyToClipboard(text) {
  3. navigator.clipboard
  4. .writeText(text)
  5. .then(() => {
  6. console.log("Text copied to clipboard");
  7. })
  8. .catch((err) => {
  9. console.error("Could not copy text: ", err);
  10. });
  11. }
  12. // 使用示例
  13. copyToClipboard("Hello, world!");

2. 本地存储

现代浏览器提供了多种本地存储机制,用于在客户端存储数据,包括 LocalStorageSessionStorageIndexedDB。每种存储机制各有优缺点和适用场景。

LocalStorage 的基本操作

LocalStorage 是一种持久化存储机制,数据不会过期,除非手动删除。它非常适用于存储用户设置等数据。

示例代码:

  1. // 设置数据
  2. localStorage.setItem("username", "john_doe");
  3. // 获取数据
  4. const username = localStorage.getItem("username");
  5. console.log(username); // 输出: john_doe
  6. // 删除数据
  7. localStorage.removeItem("username");
  8. // 清空所有数据
  9. localStorage.clear();

SessionStorage 的基本操作

SessionStorage 类似于 LocalStorage,但数据只在页面会话期间有效,关闭标签页或浏览器后数据会被清除。

示例代码:

  1. // 设置数据
  2. sessionStorage.setItem("session_id", "123456");
  3. // 获取数据
  4. const sessionId = sessionStorage.getItem("session_id");
  5. console.log(sessionId); // 输出: 123456
  6. // 删除数据
  7. sessionStorage.removeItem("session_id");
  8. // 清空所有数据
  9. sessionStorage.clear();

IndexedDB 的基本概念与使用

IndexedDB 是一种低级 API,用于在客户端存储大量结构化数据。它支持事务、索引和搜索,适用于需要存储大量数据的应用。

示例代码:

  1. // 打开数据库
  2. const request = indexedDB.open("myDatabase", 1);
  3. request.onsuccess = function (event) {
  4. const db = event.target.result;
  5. console.log("Database opened successfully");
  6. };
  7. request.onupgradeneeded = function (event) {
  8. const db = event.target.result;
  9. // 创建对象存储
  10. const objectStore = db.createObjectStore("users", { keyPath: "id" });
  11. // 创建索引
  12. objectStore.createIndex("name", "name", { unique: false });
  13. };
  14. request.onerror = function (event) {
  15. console.error("Database error:", event.target.errorCode);
  16. };

3. 实战练习

通过本章所学知识,我们来实现一个简单的记事本应用,结合 LocalStorage 实现数据的持久化存储。

实现一个简单的记事本应用

我们的记事本应用需要以下功能:

  1. 添加新记事
  2. 显示所有记事
  3. 删除记事

HTML 结构:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>记事本应用</title>
  7. </head>
  8. <body>
  9. <h1>记事本应用</h1>
  10. <input type="text" id="note-input" placeholder="输入记事内容" />
  11. <button onclick="addNote()">添加记事</button>
  12. <ul id="notes-list"></ul>
  13. <script src="app.js"></script>
  14. </body>
  15. </html>

JavaScript 代码:

  1. // 获取 DOM 元素
  2. const noteInput = document.getElementById("note-input");
  3. const notesList = document.getElementById("notes-list");
  4. // 加载已保存的记事
  5. document.addEventListener("DOMContentLoaded", loadNotes);
  6. function addNote() {
  7. const noteText = noteInput.value.trim();
  8. if (noteText === "") return;
  9. // 创建记事对象
  10. const note = { id: Date.now(), text: noteText };
  11. // 保存记事到 LocalStorage
  12. let notes = JSON.parse(localStorage.getItem("notes")) || [];
  13. notes.push(note);
  14. localStorage.setItem("notes", JSON.stringify(notes));
  15. // 更新 UI
  16. appendNoteToDOM(note);
  17. noteInput.value = "";
  18. }
  19. function loadNotes() {
  20. const notes = JSON.parse(localStorage.getItem("notes")) || [];
  21. notes.forEach((note) => appendNoteToDOM(note));
  22. }
  23. function appendNoteToDOM(note) {
  24. const li = document.createElement("li");
  25. li.textContent = note.text;
  26. li.dataset.id = note.id;
  27. // 添加删除按钮
  28. const deleteBtn = document.createElement("button");
  29. deleteBtn.textContent = "删除";
  30. deleteBtn.onclick = function () {
  31. deleteNote(note.id);
  32. };
  33. li.appendChild(deleteBtn);
  34. notesList.appendChild(li);
  35. }
  36. function deleteNote(id) {
  37. let notes = JSON.parse(localStorage.getItem("notes")) || [];
  38. notes = notes.filter((note) => note.id !== id);
  39. localStorage.setItem("notes", JSON.stringify(notes));
  40. // 更新 UI
  41. const noteElement = document.querySelector(`li[data-id='${id}']`);
  42. notesList.removeChild(noteElement);
  43. }

实现数据的持久化存储

通过以上代码,我们实现了一个简单的记事本应用,能够添加、显示和删除记事,并将数据持久化存储在 LocalStorage 中。这样,即使刷新页面或关闭浏览器,记事内容也能够保留。

本章介绍了常用的浏览器 API 和本地存储技术,包括 Fetch API、剪贴板 API、LocalStorageSessionStorageIndexedDB。通过这些知识,你可以开发出功能更丰富、用户体验更好的 Web 应用。