2016-05-23 17 views
0

Ich muss eine IndexedDB löschen und/oder löschen können, wenn der Benutzer auf meine Website zurückkehrt. Ich möchte, dass meine Datenbank jedes Mal neu ist, wenn ich mich anmelde.IndexedDB wie wird die Datenbank beim Einloggen gelöscht?

Wie lösche oder lösche ich alle Objektspeicher in einer Datenbank, wenn ich eine Seite direkt lade?

Irgendwelche Gedanken dazu, wie man das macht?

Code:

<!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> 

Antwort

0

Dieser Code macht was ich will. Ich habe die Idee von diesem Posten: http://www.scriptscoop2.com/t/9f4135c0bf79/javascript-indexeddb-doesnt-reset-version-when-you-delete-a-database-on-chrome-bu.html [diese Seite scheint nach unten gegangen zu sein, aber es war am Dienstag nach oben] Website scheint, als von 6/8/16

Laden Daten zurück bis zu sein von peopleData in die IndexedDB, wenn sie geladen wird. Es löscht die IndexedDB beim Eingeben und Neuladen, aber NICHT beim Aktualisieren.

Klicken Sie auf Drucken Schaltfläche, um Daten in IndexedDB anzuzeigen, klicken Sie auf die Schaltfläche Hinzufügen Datensätze aus peopleData2 hinzufügen, dann auf Drucken-Taste erneut klicken ...

<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. eine Listener-Funktion für das Login-Ereignis erstellen oder Load-Ereignis oder was auch immer
  2. Increment einer Datenbankversion
  3. öffnen Sie eine Verbindung zu IndexedDB mit der neuen Version
  4. Problemspeicher löschen oder löschen Anforderungen in der onupgradeeneded Funktion

Bearbeiten: Hier ist ein Beispiel Pseudo-Code als Reaktion auf Ihre Kommentare.

<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

Könnte ich so etwas wie dies für die „Version“ verwenden: 'neue Date(). GetUTCMilliseconds() ' – MB34

+0

Sie müssen den Objektspeicher im' onupgradeeneeded' erhalten, um es zu löschen/löschen, und zu diesem Zeitpunkt ist die Datenbank noch nicht geöffnet, so dass Sie den Objektspeicher nicht bekommen können. Wenn Sie das "evt.currentTarget.result" übergeben, um den Objektspeicher abzurufen, erhalten Sie einen Fehler, der versucht, die Transaktion zu verwenden, um es zu erhalten. 'var tx = db.transaction ('docs', 'readwrite'); Rückgabe tx.objectStore ('docs');': 'Fehler beim Ausführen von 'transaction' in 'IDBDatabase': Eine Versionswechseltransaktion läuft. ' – MB34

+0

Code oben angezeigt. – MB34