2016-05-23 7 views
0

ユーザーが自分のサイトに戻ったときにIndexedDBをクリアしたり削除したりできるようにする必要があります。ログインするたびに私のDBを新鮮にしたい。IndexedDBログイン時にDBをクリアする方法は?

ページの読み込み中にDB内のすべてのオブジェクトストアをクリアまたは削除するにはどうすればよいですか?

これを行う方法についてのご意見はありますか?

コード:

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="utf-8" /> 
     <title>IndexedDB test</title> 
     <script type="text/javascript"> 
      var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; 
      var IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction; 
      var db; 
      (function() {  
       var peopleData = [ 
           {"FILENAME":"/NewDesigMemo1026732160521.pdf","DOC":"5/23/2016 | New Desig Memo","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CIC","PRG_CODE":"","DIST":"","CNAME":""}, 
           {"FILENAME":"/NewDesigMemo1026732160521.pdf","DOC":"5/23/2016 | New Desig Memo","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CISR","PRG_CODE":"","DIST":"","CNAME":""}, 
           {"FILENAME":"/AttendanceOutOfStateMemo102673220160521.pdf","DOC":"5/23/2016 | Attendance Out of State Memo","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CISR","PRG_CODE":"","DIST":"","CNAME":""}, 
           {"FILENAME":"/Attend1026732160521.pdf","DOC":"5/23/2016 | Attendance","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CSRM","PRG_CODE":"","DIST":"","CNAME":""}, 
           {"FILENAME":"/NewMemo1026732160521.pdf","DOC":"5/23/2016 | New Desig Memo","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CRM","PRG_CODE":"","DIST":"","CNAME":""}, 
           ]; 

       var peopleData2 = [ 
            {"FILENAME":"/Attend102673220160312.pdf","PRT_DATE":"3/14/2016","EC":"","DOC":"3/14/2016 | CSRM Attendance","CRID":null,"PRG_CODE":"","STATE":"","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"","DIST":null,"CNAME":""}, 
            {"FILENAME":"/RMagazine.aspx?I=r_spring_2016&P=1026732","PRT_DATE":"","EC":"","DOC":"R Magazine Spring 2016","CRID":null,"PRG_CODE":"","STATE":"","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"Spring 2016","DIST":null,"CNAME":""}, 
            {"FILENAME":"/Packet+Notification+CISR+CIC+20160309ALM.html","PRT_DATE":"3/9/2016","EC":"20160317LLM","DOC":"3/9/2016 | Packet Notification","CRID":null,"PRG_CODE":"","STATE":"","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"","DIST":null,"CNAME":"WTH"}, 
            {"FILENAME":"Eval20160317LLM1026732.pdf","PRT_DATE":"","EC":"20160317LLM","DOC":"Evaluation_Packet","CRID":null,"PRG_CODE":"ALM","STATE":"LA","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"","DIST":null,"CNAME":"WTH"}, 
            {"FILENAME":"Eval20160315LPR1026732.pdf","PRT_DATE":"","EC":"20160315LPR","DOC":"Evaluation_Packet","CRID":null,"PRG_CODE":"PR","STATE":"LA","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"","DIST":null,"CNAME":"IPR"} 
           ] 

       function initDb() { 
        var request = indexedDB.open("DocsDB", new Date().getUTCMilliseconds()); 
        request.onsuccess = function (evt) { 
         db = request.result;  
         // Only do the below if this is first visit to page...              
         if(window.performance) { 
          if(performance.navigation.type == 0) { 
           var store = getObjectStore(db);     
           // The db already exists so delete it and re-create it so we don't have stale records. 
           if(store != null) { 
            store.clear(); 
           } 
          } 
         } 
        }; 

        request.onerror = function (evt) { 
         console.log("IndexedDB error: " + evt.target.error.code); 
        }; 

        request.onupgradeneeded = function (evt) { 
         var objectStore = evt.currentTarget.result.createObjectStore(
           "docs", { keyPath: "id", autoIncrement: true }); 

         objectStore.createIndex("docname", "DOC", { unique: false }); 
         objectStore.createIndex("printdate", "PRT_DT", { unique: false }); 

         for (i in peopleData) { 
          objectStore.add(peopleData[i]); 
         } 
        }; 
       } 

       function getObjectStore(db, mode) { 
        if(typeof db != 'undefined') { 
         var tx = db.transaction('docs', 'readwrite'); 
         return tx.objectStore('docs'); 
        } else { 
         return null; 
        } 
       } 

       function contentLoaded() {   
        initDb();  
        var btnPrint = document.getElementById("btnPrint");     

        btnAdd.addEventListener("click", function() { 
         var transaction = db.transaction("docs", "readwrite"); 
         var objectStore = transaction.objectStore("docs"); 
         for (i in peopleData2) { 
          var request = objectStore.add(peopleData[i]); 
          request.onsuccess = function (evt) { 
           // do something after the add succeeded 
          }; 
         } 

        }, false); 

        btnPrint.addEventListener("click", function() { 
         var output = document.getElementById("printOutput"); 
         output.textContent = ""; 

         var transaction = db.transaction("docs", "readwrite"); 
         var objectStore = transaction.objectStore("docs"); 

         var request = objectStore.openCursor(); 
         request.onsuccess = function(evt) { 
          var cursor = evt.target.result; 
          if (cursor) { 
           output.textContent += "id: " + cursor.key + " is " + cursor.value.FILENAME + " " + cursor.value.DOC;        
           cursor.continue(); 
          } 
         }; 
        }, false);    
       } 
       window.addEventListener("DOMContentLoaded", contentLoaded, false); 
      })(); 
     </script> 
    </head> 
    <body> 
     <div id="container"> 
      <input type="button" id="btnAdd" value="Add Records" /> 
      <br /> 
      <br /> 
      <input type="button" id="btnPrint" value="Print objectStore" /> 
      <br /> 
      <br /> 
      <output id="printOutput"> 
      </output> 
     </div> 
    </body> 
</html> 

答えて

0

このコードは私がしたいことをします。私はこの記事からアイデアを得た: http://www.scriptscoop2.com/t/9f4135c0bf79/javascript-indexeddb-doesnt-reset-version-when-you-delete-a-database-on-chrome-bu.html [このサイトがダウンしているようだが、それは火曜日にアップしました]サイトは6/8/16

ロードデータのように戻るまでのようですpeopleDataからロードされたときにIndexedDBにロードされます。これは、入力時と再読み込み時にIndexedDBを削除しますが、更新時には削除しません。 `新しい:再度印刷ボタンをクリックしてください...

<html> 
    <head> 
     <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
     <script type="text/javascript"> 
      var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; 
      var db; 
      window.refreshing = false; 
      var peopleData = [ 
          {"FILENAME":"/NewDesigMemo1026732160521.pdf","DOC":"5/23/2016 | New Desig Memo","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CC","PRG_CODE":"","DIST":"","CNAME":""}, 
          {"FILENAME":"/NewDesigMemo1026732160521.pdf","DOC":"5/23/2016 | New Desig Memo","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CSR","PRG_CODE":"","DIST":"","CNAME":""}, 
          {"FILENAME":"/AttendanceOutOfStateMemo102673220160521.pdf","DOC":"5/23/2016 | Attendance Out of State Memo","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CSR","PRG_CODE":"","DIST":"","CNAME":""}, 
          {"FILENAME":"/Attend1026732160521.pdf","DOC":"5/23/2016 | Attendance","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CSM","PRG_CODE":"","DIST":"","CNAME":""}, 
          {"FILENAME":"/NewMemo1026732160521.pdf","DOC":"5/23/2016 | New Desig Memo","PRT_DT":"5/23/2016","EC":"","STATE":"","DES":"CM","PRG_CODE":"","DIST":"","CNAME":""}, 
          ]; 

      var peopleData2 = [ 
           {"FILENAME":"/Attend102673220160312.pdf","PRT_DATE":"3/14/2016","EC":"","DOC":"3/14/2016 | CSRM Attendance","CRID":null,"PRG_CODE":"","STATE":"","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"","DIST":null,"CNAME":""}, 
           {"FILENAME":"/RMagazine.aspx?I=r_spring_2016&P=1026732","PRT_DATE":"","EC":"","DOC":"R Magazine Spring 2016","CRID":null,"PRG_CODE":"","STATE":"","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"Spring 2016","DIST":null,"CNAME":""}, 
           {"FILENAME":"/Packet+Notification+CSR+CC+20160309ALM.html","PRT_DATE":"3/9/2016","EC":"20160317LLM","DOC":"3/9/2016 | Packet Notification","CRID":null,"PRG_CODE":"","STATE":"","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"","DIST":null,"CNAME":"WTH"}, 
           {"FILENAME":"Eval20160317LLM1026732.pdf","PRT_DATE":"","EC":"20160317LLM","DOC":"Evaluation_Packet","CRID":null,"PRG_CODE":"ALM","STATE":"LA","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"","DIST":null,"CNAME":"WTH"}, 
           {"FILENAME":"Eval20160315LPR1026732.pdf","PRT_DATE":"","EC":"20160315LPR","DOC":"Evaluation_Packet","CRID":null,"PRG_CODE":"PR","STATE":"LA","DES":"","DATE_SENT":null,"PRG_DESC":null,"YEAR":null,"ISSUE":"","DIST":null,"CNAME":"IPR"} 
          ] 
      function open() { 
       var request = indexedDB.open("DocsDB"); 
       var upgraded = false; 
       request.onupgradeneeded = function(evt) { 
        upgraded = true; 
        console.log("upgraded ok"); 
        var dbnew = evt.target.result; 

        dbnew.onerror = function(event) { 
         console.log("IndexedDB error: " + evt.target.error.code); 
        }; 

        var objectStore = dbnew.createObjectStore(
          "docs", { keyPath: "id", autoIncrement: true }); 

        objectStore.createIndex("docname", "DOC", { unique: false }); 
        objectStore.createIndex("printdate", "PRT_DT", { unique: false }); 
       } 
       request.onsuccess = function(evt) { 
        db = request.result; 
        if (!upgraded && !window.refreshing) { 
         throw "Not upgraded"; 
        } 
        console.log("open ok"); 
        request.result.onversionchange = function(e) { 
         if (e.newVersion === null) { // An attempt is made to delete the db 
          e.target.close(); // Manually close our connection to the db 
         } 
        }; 

        if(typeof db != 'undefined' && !window.refreshing) { 
         var store = getObjectStore(db);     
         for (i in peopleData) { 
          store.add(peopleData[i]); 
          console.log("Added:"+peopleData[i]); 
         } 
        } 
       } 
       request.onerror = function() { 
        throw "Error in open"; 
       } 
      } 

      function getObjectStore(db, mode = 'readwrite') { 
       if(typeof db != 'undefined') { 
        var tx = db.transaction('docs', mode); 
        return tx.objectStore('docs'); 
       } else { 
        return null; 
       } 
      } 

      function obliterate() { 
       var request = indexedDB.deleteDatabase("DocsDB"); 
       request.onsuccess = function() { 
        console.log("delete ok"); 
        open(); 
       } 
       request.onerror = function(event) { 
        throw "Error in obliterate."; 
       } 
      } 

      $(document).ready(function(){ 
       if(window.performance) { 
        if(performance.navigation.type == 0) { 
         // The db already exists so delete it and re-create it so we don't have stale records. 
         obliterate(); 
        } else { 
         window.refreshing = true; 
         open(); 
        } 
       } 

       $("#btnAdd").click(function() { 
        var transaction = db.transaction("docs", "readwrite"); 
        var objectStore = transaction.objectStore("docs"); 
        for (i in peopleData2) { 
         var request = objectStore.add(peopleData[i]); 
         request.onsuccess = function (evt) { 
          // do something after the add succeeded 
         }; 
        }      
       }); 

       $("#btnPrint").click(function() {     
        var output = $("#printOutput"); 
        output.html(""); 

        var transaction = db.transaction("docs", "readwrite"); 
        var objectStore = transaction.objectStore("docs"); 

        var request = objectStore.openCursor(); 
        request.onsuccess = function(evt) { 
         var cursor = evt.target.result; 
         if (cursor) { 
          output.html(output.html() + JSON.stringify(cursor.value) + '<br />'); 
          cursor.continue(); 
         } 
        }; 
       });       

      }); 
     </script> 
    </head> 
    <body> 
    <!-- http://localhost:8040/idb_test3.html --> 
     <div id="container"> 
      <input type="button" id="btnAdd" value="Add Records" /> 
      <br /> 
      <br /> 
      <input type="button" id="btnPrint" value="Print objectStore" /> 
      <br /> 
      <br /> 
      <output id="printOutput"> 
      </output> 
     </div> 
    </body> 
</html> 
0
  1. は、ログインイベントまたはloadイベントや のリスナー関数を作成しますどんな
  2. インクリメントデータベースのバージョン
  3. オープンの新しいバージョンとのIndexedDBへの接続
  4. onupgradeneeded関数のストアの削除要求またはクリア要求

編集:あなたのコメントに対する擬似コードの例を示します。

<script type="application/javascript"> 

(function() { // BEGIN IIFE 

// Get the current db version 
var dbVersionString = localStorage.DB_VERSION || '0'; 
var dbVersion = parseInt(dbVersionString, 10); 

// Increment the version and store it so next page load knows 
dbVersion++; 
localStorage.DB_VERSION = '' + dbVersion; 

// Open a connection using the new version 
var openRequest = indexedDB.open('mydb', dbVersion); 
openRequest.onupgradeneeded = myOnUpgradeNeeded; 
openRequest.onerror = console.error; 

// Opening a new conn with higher version triggers this 
// upgrade callback 
function myOnUpgradeNeeded(event) { 
    // Get the connection variable 
    var openRequest = event.target; 
    var db = openRequest.result; 

    // Reference the implicit versionchange transaction 
    var tx = openRequest.transaction; 

    // NOTE: this is assuming you only have 1 store. Otherwise you can 
    // loop over objectStoreNames, or you can just maintain your own 
    // list of known names and loop over that here. 

    var docsStore; 

    if(!db.objectStoreNames.contains('docs')) { 
    // Create the store 
    docsStore = db.createObjectStore('docs'); 
    docsStore.createIndex(...); 
    } else { 
    // Get and clear the existing store 
    docsStore = tx.objectStore('docs'); 
    docsStore.clear(); 
    } 

    // Put stuff in the store 
    for(var i = 0, len = peopleData.length; i < len; i++) { 
    docsStore.put(peopleData[i]); 
    } 
} 

}()); // END IIFE 

</script> 
+0

が、私は「バージョン」のためにこのようなものを使用することができ、peopleData2からレコードを追加するボタンを追加し、のIndexedDBでデータを表示]をクリックする

クリックして印刷ボタンDate()。getUTCMilliseconds() ' – MB34

+0

これをクリア/削除するには、onupgradeneededでobjectStoreを取得する必要があります。この時点でdbはオープンされていないため、objectStoreを取得できません。また、 'evt.currentTarget.result'を渡してobjectStoreを取得した場合、取得するためにトランザクションを使用しようとしてエラーが発生します。 'IDBDatabase'で 'transaction'を実行できませんでした:バージョン変更トランザクションが実行中です。 ' – MB34

+0

(' docs '、' readwrite '); tx.objectStore(' docs ');上記のコードを表示します。 – MB34

関連する問題