You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PhoneGap iOS应用出现Cannot read property 'transaction' of undefined错误

Fixing "Cannot read property 'transaction' of undefined" in PhoneGap iOS with cordova-sqlite-storage

Hey there, that error means your myDB variable is still undefined when you try to call .transaction() on it—so the database connection isn't being established properly. Let's break down the possible issues and fixes step by step:

1. Your database code isn't waiting for the deviceready event

This is the most common culprit! Cordova plugins (including the SQLite storage plugin) only become available after the deviceready event fires. You mentioned using $(document).ready(), but that fires when the DOM is ready—not when Cordova has loaded all plugins and device APIs are ready.

Make sure every part of your database code lives inside the deviceready callback:

$(document).ready(function(){
  // Wait for Cordova to fully initialize first!
  document.addEventListener("deviceready", function() {
    // Now safely initialize the database
    var myDB = window.sqlitePlugin.openDatabase({
      name: "myDatabase.db",
      location: 'default' // Required for iOS platform
    });

    // Now you can use myDB.transaction() without errors
    myDB.transaction(function(tx) {
      tx.executeSql('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)');
    }, function(error) {
      console.error('Transaction failed: ' + error.message);
    }, function() {
      console.log('Database setup successful!');
    });
  }, false);
});

2. Verify the cordova-sqlite-storage plugin is properly installed

Double-check that the plugin is actually added to your project:

  • Open your project's root folder in a terminal
  • Run cordova plugin list
  • You should see cordova-sqlite-storage listed. If not, install it with:
    cordova plugin add cordova-sqlite-storage
    

After installing, rebuild your iOS project to apply changes:

cordova build ios

3. Ensure your PhoneGap environment is synced

Sometimes PhoneGap Desktop can get out of sync with your project files:

  • Close and re-open PhoneGap Desktop
  • Confirm you've selected the correct project folder
  • Try reloading the app on your iOS device or emulator

4. Don't confuse WebSQL with the SQLite plugin

Avoid using the plain openDatabase() function (that's for WebSQL). The cordova-sqlite-storage plugin requires you to use window.sqlitePlugin.openDatabase() explicitly—this mix-up is a common cause of undefined database instances.


内容的提问来源于stack exchange,提问作者user9562782

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:18:17