آموزش HTML - ذخیره‌سازی محلی مرورگر( IndexedDB)

مفهوم indexedDB یک مفهوم جدید در HTML5 برای ذخیره‌سازی داده‌ها در مرورگر کاربر است. این قابلیت قدرتمندتر از local storage است و برای برنامه‌هایی که نیاز به ذخیره حجم زیادی از داده‌ها دارند، بسیار مفید است. این برنامه‌ها می‌توانند با کارایی بیشتر اجرا شوند و سریع‌تر بارگذاری شوند.

چرا باید از indexedDB استفاده کنیم؟

کن کنسرسیوم وب (W3C) اعلام کرده است که پایگاه داده Web SQL یک مشخصه منسوخ‌شده برای ذخیره‌سازی محلی است، بنابراین توسعه‌دهندگان وب نباید دیگر از این فناوری استفاده کنند. پایگاه داده indexedDB جایگزینی برای Web SQL است و کارایی بیشتری نسبت به فناوری‌های قدیمی‌تر دارد.

ویژگی‌ها

  • داده‌ها را به صورت جفت‌های کلید-مقدار (key-pair) ذخیره می‌کند

  • یک پایگاه داده رابطه‌ای نیست

  • رابط برنامه‌نویسی (API) مربوط به IndexedDB عمدتاً ناهمگام (asynchronous) است

  • یک زبان پرس‌وجوی ساختاریافته (SQL) نیست

  • امکان دسترسی به داده‌ها را از همان دامنه (same domain) فراهم می‌کند

IndexedDB

قبل از ورود به indexedDB، باید برخی از پیشوندهای پیاده‌سازی را همان‌طور که در زیر نشان داده شده است اضافه کنیم −

window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;

window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange

if (!window.indexedDB) {
   window.alert("Your browser doesn't support a stable version of IndexedDB.")
}

باز کردن یک پایگاه داده IndexedDB

قبل از ایجاد یک پایگاه داده، باید برخی داده‌ها را برای آن آماده کنیم. بیایید با جزئیات کارمندان شرکت شروع کنیم.

const employeeData = [
   { id: "01", name: "Gopal K Varma", age: 35, email: "contact@tutorialspoint.com" },
   { id: "02", name: "Prasad", age: 24, email: "prasad@tutorialspoint.com" }
];

افزودن داده‌ها

در اینجا نحوه افزودن دستی برخی داده‌ها به پایگاه داده به صورت زیر نشان داده شده است −

function add() {
   var request = db.transaction(["employee"], "readwrite")
   .objectStore("employee")
   .add({ id: "01", name: "prasad", age: 24, email: "prasad@tutorialspoint.com" });
   
   request.onsuccess = function(event) {
      alert("Prasad has been added to your database.");
   };
   
   request.onerror = function(event) {
      alert("Unable to add data\r\nPrasad is already exist in your database! ");
   }
}

بازیابی داده‌ها

ما می‌توانیم با استفاده از ()get داده‌ها را از پایگاه داده بازیابی کنیم

function read() {
   var transaction = db.transaction(["employee"]);
   var objectStore = transaction.objectStore("employee");
   var request = objectStore.get("00-03");
   
   request.onerror = function(event) {
      alert("Unable to retrieve daa from database!");
   };
   
   request.onsuccess = function(event) {
      if(request.result) {
         alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
      } else {
         alert("Kenny couldn't be found in your database!");
      }
   };
}

با استفاده از ()get می‌توانیم داده‌ها را در یک شیء ذخیره کنیم؛ به جای آن می‌توانیم داده‌ها را در مکان‌نما (cursor) ذخیره کرده و از طریق مکان‌نما بازیابی کنیم

function readAll() {
   var objectStore = db.transaction("employee").objectStore("employee");
   
   objectStore.openCursor().onsuccess = function(event) {
      var cursor = event.target.result;
      
      if (cursor) {
         alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
         cursor.continue();
      } else {
         alert("No more entries!");
      }
   };
}

حذف داده‌ها

ما می‌توانیم داده‌ها را با استفاده از متد ()remove از IndexedDB حذف کنیم. کد آن به صورت زیر است −

function remove() {
   var request = db.transaction(["employee"], "readwrite")
   .objectStore("employee")
   .delete("02");
   
   request.onsuccess = function(event) {
      alert("prasad entry has been removed from your database.");
   };
}

کد HTML

برای نمایش تمامی داده‌ها باید از رویداد onClick مطابق کد زیر استفاده کنیم −

<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <title>IndexedDb Demo | onlyWebPro.com</title>
</head>
<body>
   <button onclick="read()">Read </button>
   <button onclick="readAll()"></button>
   <button onclick="add()"></button>
   <button onclick="remove()">Delete </button>
</body>
</html>

کد نهایی باید به این صورت باشد −

<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
   <script type="text/javascript">
      
      //prefixes of implementation that we want to test
      window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
      
      //prefixes of window.IDB objects
      window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
      window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange
      
      if (!window.indexedDB) {
         window.alert("Your browser doesn't support a stable version of IndexedDB.")
      }
      
      const employeeData = [
         { id: "00-01", name: "gopal", age: 35, email: "gopal@tutorialspoint.com" },
         { id: "00-02", name: "prasad", age: 32, email: "prasad@tutorialspoint.com" }
      ];
      var db;
      var request = window.indexedDB.open("newDatabase", 1);
      
      request.onerror = function(event) {
         console.log("error: ");
      };
      
      request.onsuccess = function(event) {
         db = request.result;
         console.log("success: "+ db);
      };
      
      request.onupgradeneeded = function(event) {
         var db = event.target.result;
         var objectStore = db.createObjectStore("employee", {keyPath: "id"});
         
         for (var i in employeeData) {
            objectStore.add(employeeData[i]);
         }
      }
      function read() {
         var transaction = db.transaction(["employee"]);
         var objectStore = transaction.objectStore("employee");
         var request = objectStore.get("00-03");
         
         request.onerror = function(event) {
            alert("Unable to retrieve daa from database!");
         };
         request.onsuccess = function(event) {
            
            // Do something with the request.result!
            if(request.result) {
               alert("Name: " + request.result.name + ", Age: " + request.result.age + ", Email: " + request.result.email);
            } else {
               alert("Kenny couldn't be found in your database!");
            }
         };
      }
      
      function readAll() {
         var objectStore = db.transaction("employee").objectStore("employee");
         objectStore.openCursor().onsuccess = function(event) {
            var cursor = event.target.result;
            
            if (cursor) {
               alert("Name for id " + cursor.key + " is " + cursor.value.name + ", Age: " + cursor.value.age + ", Email: " + cursor.value.email);
               cursor.continue();
            } else {
               alert("No more entries!");
            }
         };
      }
      
      function add() {
         var request = db.transaction(["employee"], "readwrite")
         .objectStore("employee")
         .add({ id: "00-03", name: "Kenny", age: 19, email: "kenny@planet.org" });
         
         request.onsuccess = function(event) {
            alert("Kenny has been added to your database.");
         };
         request.onerror = function(event) {
            alert("Unable to add data\r\nKenny is aready exist in your database! ");
         }
      }
      
      function remove() {
         var request = db.transaction(["employee"], "readwrite")
         .objectStore("employee")
         .delete("00-03");
         
         request.onsuccess = function(event) {
            alert("Kenny's entry has been removed from your database.");
         };
      }
   </script>
</head>
<body>
   <button onclick="read()">Read </button>
   <button onclick="readAll()">Read all </button>
   <button onclick="add()">Add data </button>
   <button onclick="remove()">Delete data </button>
</body>
</html>

پیشرفت مطالعه: وضعیت خوانده‌شدن این درس فقط در همین مرورگر ذخیره می‌شود؛ بدون نیاز به حساب کاربری.