使用已知的 db 版本初始化資料庫 - 建立表

為了觸發 upgradeneeded 事件,你需要使用高於當前版本的版本請求資料庫 - 否則將不會觸發事件。

function createTable(dbName, dbversion, tableName) {
  var request = indexedDB.open(dbName, dbversion);
  request.onupgradeneeded = function (e) {
    var database = e.target.result;
    var objectStore = database.createObjectStore(tableName, {
        keyPath: 'id'
    });
    console.log("Object Store Created");
  };
  request.onsuccess = function (e) {
    var database = e.target.result;
    
    //code to verify that the table was created    
    database.objectStoreNames.contains(storeName);
        
    database.close();
  }
  request.onerror = function (e) {
    console.error(e.target.error.message);
  }
}