IndexedDB无法在Firefox 29中运行,但在Chrome中运行

时间:2014-06-23 15:55:28

标签: firefox indexeddb

我遇到问题我使用您的控制台在Chrome IndexedDB上开发了50%的代码。但是要在Firefox上测试这段代码,我注意到它不起作用。

异步函数不调用此JavaScript Firefox包含在HTML中:

<script src="./js/bdLocal.js"></script>

bdLocal.js:

var db;

function openDB() {
   console.log("openDB ") ;
   var request = indexedDB.open("dblocal",1);
   //db = request.result;

   request.onerror = function(event) {
      console.log("Database error: " + event.target.errorCode);
   };

   request.onsuccess = function(event) {
      console.log("Database onsuccess: " );
      db = request.result;
   };

   request.onupgradeneeded = function(event) { 
       console.log("onupgradeneeded");  

       var db = event.target.result;

       var objectStore = db.createObjectStore("customers", { keyPath: "ssn" });

       objectStore.createIndex("name", "name", { unique: true });
       objectStore.createIndex("email", "email", { unique: true });
       objectStore.createIndex("matricula", "matricula", { unique: false });
   };
}

1 个答案:

答案 0 :(得分:1)

您可能正在尝试同步使用异步功能。不幸的是,Mozilla网站上的示例在这一点上非常错误。不幸的是,HTML5Rocks上的几个例子也是如此。以下方法会在任何浏览器中导致很多问题:

var unreliableGlobalDatabaseConnectionVariable;
var request = indexedDB.open(...);
request.onsuccess = function() {
  var reliableDatabaseConnectionVariable = request.result;
  unreliableGlobalDatabaseConnectionVariable = reliableDatabaseConnectionVariable;
};

var transaction = unreliableGlobalDatabaseConnectionVariable.transaction(...);
// etc.

indexedDB.open是一个异步函数。这意味着许多事情,其中​​两个在这里需要指出:

  1. 在request.onsuccess执行之前,全局db变量将一直未定义。因此,在此时间点之前访问全局变量的任何尝试都将无效,因为此时变量未定义。在同一范围内的request.onsuccess之后的任何代码都是同步的,因此在之前也可能是。即使是新行上的代码,在之前仍然是
  2. 一旦request.onsuccess完成,那么全局db变量可能在之后的任何时间点变为关闭,null或未定义,或者无用。它可能是1纳秒之后,它可能是5毫秒之后,它可能是一个小时后,它可能永远不会。之后无法保证数据库连接保持打开状态。通常,在连接器上没有打开实时事务后,某些使indexedDB工作的人在浏览器中工作的方式导致数据库连接被关闭一段时间。
  3. 尝试尝试以下方法:

    var openDatabaseRequest = indexedDB.open(name,version);
    
    openDatabaseRequest.onsuccess = function(event) {
      console.log('Connected');
      var db = openDatabaseRequest.result;
    
      // Only access the db variable within this function
      // where it is guaranteed to be defined and open 
      // for the scope (all statements inside) of this function. For example,
      // do puts and gets and open cursors only inside this 
      // function.
      var transaction = db.transaction(...);
      var store = transaction.objectStore(...);
      var request = store.put(...);
      request.onsuccess = function() {
        console.log('put was successful');
      };
    };
    

    这个问题可能与以下内容重复:

    这个问题实际上与indexedDB无关,但与Javascript中使用异步代码有关。因此,它可能与使用XMLHttpRequest的数百个问题重复。