Safari不支持indexedDB.databases()

时间:2019-09-04 11:13:36

标签: javascript indexeddb

我正在使用Safari 12.1,并使用javascript处理IndexedDB。 我需要获取所有indexedDB数据库名称,但是Safari浏览器不支持indexedDB.databases()函数enter image description here chrome enter image description here

支持

那么如何在Safari中获取所有indexedDB数据库?

请帮助。

2 个答案:

答案 0 :(得分:1)

从2019年8月29日开始使用safari v13.0.1更好看, 因此,请尝试使用Safari技术预览版。

请检查:

https://caniuse.com/#feat=indexeddb

safari

https://bugs.webkit.org

https://github.com/dfahlander/Dexie.js/issues

答案 1 :(得分:1)

/**
 * Polyfill for indexedDB.databases()
 * Safari and some other older browsers that support indexedDB do NOT
 * Support enumerating existing databases. This is problematic when it
 * comes time to cleanup, otherwise we could litter their device with
 * unreferenceable database handles forcing a nuclear browser clear all history.
 */

(function () {
    if (window.indexedDB && typeof window.indexedDB.databases === 'undefined') {
        const LOCALSTORAGE_CACHE_KEY = 'indexedDBDatabases';

        // Store a key value map of databases
        const getFromStorage = () =>
            JSON.parse(window.localStorage[LOCALSTORAGE_CACHE_KEY] || '{}');

        // Write the database to local storage
        const writeToStorage = value =>
            (window.localStorage[LOCALSTORAGE_CACHE_KEY] = JSON.stringify(value));

        IDBFactory.prototype.databases = () =>
            Promise.resolve(
                Object.entries(getFromStorage()).reduce((acc, [name, version]) => {
                    acc.push({ name, version });
                    return acc;
                }, [])
            );

        // Intercept the existing open handler to write our DBs names
        // and versions to localStorage
        const open = IDBFactory.prototype.open;

        IDBFactory.prototype.open = function (...args) {
            const dbName = args[0];
            const version = args[1] || 1;
            const existing = getFromStorage();
            writeToStorage({ ...existing, [dbName]: version });
            return open.apply(this, args);
        };

        // Intercept the existing deleteDatabase handler remove our
        // dbNames from localStorage
        const deleteDatabase = IDBFactory.prototype.deleteDatabase;

        IDBFactory.prototype.deleteDatabase = function (...args) {
            const dbName = args[0];
            const existing = getFromStorage();
            delete existing[dbName];
            writeToStorage(existing);
            return deleteDatabase.apply(this, args);
        };
    }
})();