profile
viewpoint

Ask questionslocalforage causing race conditions with IndexedDB and WebSQL

Interesting bug that took me forever to track down.

Basically, unless you explicitly set driver in localforage.config, Chrome and Safari are indeterministic about which driver they will use, resulting in what "seems" like data loss. This happens at random.

So basically, I have 2 databases, and I'll be connected to one of them through localforage on any given reload.

UPDATE:

IndexedDB detection flat out fails half the time on chrome. I've tried debugging this for the past hour and haven't made any progress. Setting the driver explicitly to indexeddb leads to "storage not found" errors.

localForage/localForage

Answer questions mareksuscak

I found the root cause of the issue in the function that detects if isIndexDb is valid.

The issue here is that browsers can be emulating behaviors with polyfills. My specific issue is even more cryptic: My last pass extension in Chrome overrides window.fetch so it is no longer a native function.

function isIndexedDBValid() {
    try {
        // Initialize IndexedDB; fall back to vendor-prefixed versions
        // if needed.
        console.log('1');
        if (!idb) {
            return false;
        }
        // We mimic PouchDB here;
        //
        // We test for openDatabase because IE Mobile identifies itself
        // as Safari. Oh the lulz...
        var isSafari = typeof openDatabase !== 'undefined' && /(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent) && !/BlackBerry/.test(navigator.platform);
        // THIS IS OVER PROTECTIVE. JUST LET A WINDOW.FETCH FUNCTION THROUGH
        var hasFetch = typeof fetch === 'function' && fetch.toString().indexOf('[native code') !== -1;

        // Safari <10.1 does not meet our requirements for IDB support (#5572)
        // since Safari 10.1 shipped with fetch, we can use that to detect it
        return (!isSafari || hasFetch) && typeof indexedDB !== 'undefined' &&
        // some outdated implementations of IDB that appear on Samsung
        // and HTC Android devices <4.4 are missing IDBKeyRange
        // See: https://github.com/mozilla/localForage/issues/128
        // See: https://github.com/mozilla/localForage/issues/272
        typeof IDBKeyRange !== 'undefined';
    } catch (e) {
        return false;
    }
}

You're right. This is extremely problematic because there are lots of libraries that polyfill fetch for various reasons, e.g. Fullstory and/or Sentry polyfill it for instrumentation.

useful!

Related questions

DOMException without any detail error message hot 1
Localforage doesn't work with newer versions of Safari. hot 1
Github User Rank List