diff --git a/drift/lib/src/web/storage.dart b/drift/lib/src/web/storage.dart index 9aababc5..93d8358b 100644 --- a/drift/lib/src/web/storage.dart +++ b/drift/lib/src/web/storage.dart @@ -1,11 +1,11 @@ import 'dart:html'; import 'dart:indexed_db'; -import 'dart:js'; import 'dart:typed_data'; import 'package:meta/meta.dart'; import 'binary_string_conversion.dart'; +import 'wasm_setup/shared.dart'; /// Interface to control how drift should store data on the web. abstract class DriftWebStorage { @@ -70,25 +70,7 @@ abstract class DriftWebStorage { /// Attempts to check whether the current browser supports the /// [DriftWebStorage.indexedDb] storage implementation. static Future supportsIndexedDb({bool inWebWorker = false}) async { - var isIndexedDbSupported = false; - if (inWebWorker && WorkerGlobalScope.instance.indexedDB != null) { - isIndexedDbSupported = true; - } else { - try { - isIndexedDbSupported = IdbFactory.supported; - - if (isIndexedDbSupported) { - // Try opening a mock database to check if IndexedDB is really - // available. This avoids the problem with Firefox incorrectly - // reporting IndexedDB as supported in private mode. - final mockDb = await window.indexedDB!.open('drift_mock_db'); - mockDb.close(); - } - } catch (error) { - isIndexedDbSupported = false; - } - } - return isIndexedDbSupported && context.hasProperty('FileReader'); + return checkIndexedDbSupport(); } } diff --git a/drift/lib/src/web/wasm_setup.dart b/drift/lib/src/web/wasm_setup.dart index a3509e66..6138eafc 100644 --- a/drift/lib/src/web/wasm_setup.dart +++ b/drift/lib/src/web/wasm_setup.dart @@ -67,7 +67,8 @@ Future openWasmDatabase({ await sharedMessages.nextNoError as SharedWorkerStatus; missingFeatures.addAll(sharedFeatures.missingFeatures); - // Can we use the shared OPFS implementation? + // Prefer to use the shared worker to host the database if it supports the + // necessary APIs. if (sharedFeatures.canSpawnDedicatedWorkers && sharedFeatures.dedicatedWorkersCanUseOpfs) { return connect( diff --git a/drift/lib/src/web/wasm_setup/shared.dart b/drift/lib/src/web/wasm_setup/shared.dart index c65bb0d9..e83fe444 100644 --- a/drift/lib/src/web/wasm_setup/shared.dart +++ b/drift/lib/src/web/wasm_setup/shared.dart @@ -1,4 +1,5 @@ import 'dart:html'; +import 'dart:indexed_db'; import 'package:drift/drift.dart'; import 'package:drift/remote.dart'; @@ -54,7 +55,27 @@ Future checkOpfsSupport() async { } } +/// Checks whether IndexedDB is working in the current browser by opening a test +/// database. Future checkIndexedDbSupport() async { + if (!hasProperty(globalThis, 'indexedDB') || + // FileReader needed to read and write blobs efficiently + !hasProperty(globalThis, 'FileReader')) { + return false; + } + + final idb = getProperty(globalThis, 'indexedDB'); + + try { + const name = 'drift_mock_db'; + + final mockDb = await idb.open(name); + mockDb.close(); + idb.deleteDatabase(name); + } catch (error) { + return false; + } + return true; }