JavaScript และ StorageManager

JavaScript และ StorageManager

บทความนี้อธิบายเกี่ยวกับ JavaScript และ StorageManager

เราจะอธิบายฟีเจอร์ของ StorageManager อย่างละเอียด และแนะนำวิธีใช้งานทีละขั้นตอน พร้อมตัวอย่างโค้ดที่สามารถใช้งานได้จริงในเบราว์เซอร์

YouTube Video

javascript-storage-manager.html
  1<!DOCTYPE html>
  2<html lang="en">
  3<head>
  4  <meta charset="UTF-8">
  5  <title>JavaScript &amp; HTML</title>
  6  <style>
  7    * {
  8        box-sizing: border-box;
  9    }
 10
 11    body {
 12        margin: 0;
 13        padding: 1em;
 14        padding-bottom: 10em;
 15        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
 16        background-color: #f7f9fc;
 17        color: #333;
 18        line-height: 1.6;
 19    }
 20
 21    .container {
 22        max-width: 800px;
 23        margin: 0 auto;
 24        padding: 1em;
 25        background-color: #ffffff;
 26        border: 1px solid #ccc;
 27        border-radius: 10px;
 28        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
 29    }
 30
 31    .container-flex {
 32        display: flex;
 33        flex-wrap: wrap;
 34        gap: 2em;
 35        max-width: 1000px;
 36        margin: 0 auto;
 37        padding: 1em;
 38        background-color: #ffffff;
 39        border: 1px solid #ccc;
 40        border-radius: 10px;
 41        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
 42    }
 43
 44    .left-column, .right-column {
 45        flex: 1 1 200px;
 46        min-width: 200px;
 47    }
 48
 49    h1, h2 {
 50        font-size: 1.2rem;
 51        color: #007bff;
 52        margin-top: 0.5em;
 53        margin-bottom: 0.5em;
 54        border-left: 5px solid #007bff;
 55        padding-left: 0.6em;
 56        background-color: #e9f2ff;
 57    }
 58
 59    button {
 60        display: block;
 61        margin: 1em auto;
 62        padding: 0.75em 1.5em;
 63        font-size: 1rem;
 64        background-color: #007bff;
 65        color: white;
 66        border: none;
 67        border-radius: 6px;
 68        cursor: pointer;
 69        transition: background-color 0.3s ease;
 70    }
 71
 72    button:hover {
 73        background-color: #0056b3;
 74    }
 75
 76    #output {
 77        margin-top: 1em;
 78        background-color: #1e1e1e;
 79        color: #0f0;
 80        padding: 1em;
 81        border-radius: 8px;
 82        min-height: 200px;
 83        font-family: Consolas, monospace;
 84        font-size: 0.95rem;
 85        overflow-y: auto;
 86        white-space: pre-wrap;
 87    }
 88
 89    .highlight {
 90        outline: 3px solid #ffc107; /* yellow border */
 91        background-color: #fff8e1;  /* soft yellow background */
 92        transition: background-color 0.3s ease, outline 0.3s ease;
 93    }
 94
 95    .active {
 96        background-color: #28a745; /* green background */
 97        color: #fff;
 98        box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
 99        transition: background-color 0.3s ease, box-shadow 0.3s ease;
100    }
101  </style>
102</head>
103<body>
104    <div class="container">
105        <h1>JavaScript Console</h1>
106        <button id="executeBtn">Execute</button>
107        <div id="output"></div>
108    </div>
109
110    <script>
111        // Override console.log to display messages in the #output element
112        (function () {
113            // Override console.log
114            const originalLog = console.log;
115            console.log = function (...args) {
116                originalLog.apply(console, args);
117                const message = document.createElement('div');
118                message.textContent = args
119                    .map(arg => (typeof arg === "object" && arg !== null ? JSON.stringify(arg) : String(arg)))
120                    .join(" ");
121                output.appendChild(message);
122            };
123
124            // Override console.error
125            const originalError = console.error;
126            console.error = function (...args) {
127                originalError.apply(console, args);
128                const message = document.createElement('div');
129                message.textContent = args
130                    .map(arg => (typeof arg === "object" && arg !== null ? JSON.stringify(arg) : String(arg)))
131                    .join(" ");
132                message.style.color = 'red'; // Color error messages red
133                output.appendChild(message);
134            };
135        })();
136
137        document.getElementById('executeBtn').addEventListener('click', () => {
138            // Prevent multiple loads
139            if (document.getElementById('externalScript')) return;
140
141            const script = document.createElement('script');
142            script.src = 'javascript-storage-manager.js';
143            script.id = 'externalScript';
144            //script.onload = () => console.log('javascript-storage-manager.js loaded and executed.');
145            //script.onerror = () => console.log('Failed to load javascript-storage-manager.js.');
146            document.body.appendChild(script);
147        });
148    </script>
149</body>
150</html>

JavaScript และ StorageManager

ฟีเจอร์การจัดเก็บข้อมูลบนเว็บเช่น localStorage และ IndexedDB บนเบราว์เซอร์มีความสำคัญสำหรับการบันทึกสถานะและข้อมูลของแอปพลิเคชันไว้ในอุปกรณ์ของผู้ใช้ อย่างไรก็ตาม หากข้อมูลเกี่ยวกับการจัดการความจุและความคงทนของพื้นที่จัดเก็บมีไม่เพียงพอ อาจทำให้เกิดการสูญหายของข้อมูลโดยไม่คาดคิด

StorageManager เป็น API ที่ให้บริการโดย user agent (ส่วนใหญ่คือเบราว์เซอร์) เพื่อให้สามารถตรวจสอบและจัดการข้อมูลเกี่ยวกับ การใช้งาน และ ความคงทน ของพื้นที่จัดเก็บ

StorageManager คืออะไร?

StorageManager เป็นอ็อบเจกต์ที่เข้าถึงได้ผ่าน navigator.storage โดยมีคุณสมบัติหลักดังนี้:

  • ดึงข้อมูลเกี่ยวกับพื้นที่จัดเก็บที่ใช้ไปและพื้นที่ว่าง (navigator.storage.estimate())
  • ตรวจสอบสถานะความคงทนของพื้นที่จัดเก็บ (navigator.storage.persisted())
  • ร้องขอความคงทนของพื้นที่จัดเก็บ (navigator.storage.persist())

สิ่งนี้มีประโยชน์เป็นพิเศษหากคุณต้องการให้พื้นที่จัดเก็บมีความคงทนใน Service Workers หรือ PWAs (Progressive Web Apps)

การตรวจสอบความพร้อมใช้งาน

ก่อนอื่น ตรวจสอบว่าเบราว์เซอร์รองรับ StorageManager หรือไม่

1if ('storage' in navigator && 'estimate' in navigator.storage) {
2    console.log("StorageManager is supported.");
3} else {
4    console.warn("StorageManager is not supported in this browser.");
5}
  • สามารถตรวจสอบการรองรับได้โดยดูว่าอ็อบเจกต์ navigator.storage มีอยู่และมีเมทอด estimate หรือไม่

การดึงข้อมูลการใช้พื้นที่จัดเก็บ

การใช้ navigator.storage.estimate() จะช่วยให้คุณทราบข้อมูลพื้นที่จัดเก็บที่แอปของคุณกำลังใช้งาน และโควต้าพื้นที่จัดเก็บทั้งหมด

 1async function showStorageUsage() {
 2    if (!navigator.storage || !navigator.storage.estimate) {
 3        console.warn("StorageManager is not supported.");
 4        return;
 5    }
 6
 7    const { usage, quota } = await navigator.storage.estimate();
 8    console.log(`Used: ${(usage / 1024 / 1024).toFixed(2)} MB`);
 9    console.log(`Total: ${(quota / 1024 / 1024).toFixed(2)} MB`);
10    console.log(`Usage percentage: ${(usage / quota * 100).toFixed(2)}%`);
11}
12
13showStorageUsage();
  • usage คือการใช้งานปัจจุบันในหน่วยไบต์ และ quota คือความจุสูงสุดที่สามารถใช้ได้ คุณสามารถติดตามการใช้พื้นที่จัดเก็บเพื่อแจ้งเตือนผู้ใช้เมื่อแอปของคุณใกล้ถึงขีดจำกัดของพื้นที่จัดเก็บและการใช้งานอื่น ๆ

การตรวจสอบความคงทนของพื้นที่จัดเก็บ

ในเบราว์เซอร์หลายตัว พื้นที่จัดเก็บจะถูกบันทึกเป็น 'ชั่วคราว' ซึ่งหมายความว่า ข้อมูลอาจถูกลบโดยอัตโนมัติหากพื้นที่ดิสก์ไม่เพียงพอ โดยใช้เมทอด persisted() คุณสามารถตรวจสอบได้ว่าพื้นที่จัดเก็บปัจจุบันมีความคงทนหรือไม่

1async function checkPersistence() {
2    const isPersisted = await navigator.storage.persisted();
3    console.log(`Persistent storage: ${isPersisted ? "Yes" : "No"}`);
4}
5
6checkPersistence();

การร้องขอความคงทนของพื้นที่จัดเก็บ

หากยังไม่มีความคงทน คุณสามารถร้องขอให้เบราว์เซอร์ทำให้มีความคงทนได้โดยใช้ persist() อย่างไรก็ตาม อาจถูกปฏิเสธได้ขึ้นอยู่กับการกระทำของผู้ใช้หรือเงื่อนไขบางอย่าง

1async function requestPersistence() {
2    const granted = await navigator.storage.persist();
3    console.log(`Persistence request ${granted ? "granted" : "denied"}`);
4}
5
6requestPersistence();

ในเบราว์เซอร์หลายตัว การมีเงื่อนไขดังต่อไปนี้จะเพิ่มโอกาสในการได้รับความคงทน:

  • แอปถูกติดตั้งเป็น PWA
  • ผู้ใช้ใช้งานแอปบ่อยครั้ง
  • แอปกำลังทำงานในสภาพแวดล้อมที่เป็น HTTPS
  • การร้องขอความคงทนถูกเชื่อมโยงกับการกระทำของผู้ใช้ เช่น การคลิก

ตัวอย่างเชิงปฏิบัติ: การร้องขอความคงทนจากผู้ใช้เมื่อยังไม่มีความคงทน

 1async function ensurePersistence() {
 2    const isPersisted = await navigator.storage.persisted();
 3    if (isPersisted) {
 4        console.log("Already using persistent storage.");
 5        return;
 6    }
 7
 8    const granted = await navigator.storage.persist();
 9    if (granted) {
10        alert("Storage has been set to persistent.");
11    } else {
12        alert("Unable to set persistent storage. Your data may be deleted.");
13    }
14}
15
16document.querySelector("#persistButton").addEventListener("click", ensurePersistence);
  • ในตัวอย่างนี้ จะมีการร้องขอความคงทนเมื่อผู้ใช้คลิกปุ่ม การใช้ปุ่มทำให้การร้องขอเกิดขึ้นภายใต้การกระทำของผู้ใช้ ซึ่งเพิ่มโอกาสที่จะได้รับการอนุญาต

ข้อควรระวังและความเข้ากันได้

  • navigator.storage สามารถใช้งานได้เฉพาะใน สภาพแวดล้อม HTTPS เท่านั้น
  • เบราว์เซอร์หลัก (Chrome, Edge, Firefox) รองรับฟีเจอร์นี้ แต่บางฟีเจอร์มีข้อจำกัดใน Safari
  • quota ขึ้นอยู่กับเงื่อนไขของพื้นที่จัดเก็บในแต่ละอุปกรณ์ และอาจแตกต่างกันไปในแต่ละอุปกรณ์สำหรับเว็บไซต์เดียวกัน

สรุป

ด้วยการใช้ StorageManager แอปพลิเคชันเว็บสามารถใช้พื้นที่จัดเก็บในอุปกรณ์ของผู้ใช้อย่างปลอดภัยและมียุทธศาสตร์มากขึ้น มันมีคุณสมบัติหลักดังต่อไปนี้:

  • คุณสามารถตรวจสอบการใช้พื้นที่จัดเก็บด้วย estimate()
  • คุณสามารถตรวจสอบสถานะความคงทนด้วย persisted()
  • คุณสามารถร้องขอความคงทนด้วย persist()

เมื่อพัฒนา PWA หรือแอปที่เน้นการทำงานแบบออฟไลน์ การใช้ StorageManager จะช่วยให้คุณปรับปรุงประสบการณ์ของผู้ใช้และเพิ่มการปกป้องข้อมูล

คุณสามารถติดตามบทความข้างต้นโดยใช้ Visual Studio Code บนช่อง YouTube ของเรา กรุณาตรวจสอบช่อง YouTube ด้วย

YouTube Video