0

I am using WebExtensions to port a Chrome Extension to Firefox.

As StorageArea.getBytesInUse(); is not supported in FireFox, is there any workaround to get the total size of the local storage object?

I need this to call a clearCache function when the storage is near its limit.

Julius S.
  • 664
  • 9
  • 21
  • 1
    Apparently, current FF implementation of `.set` [intercepts exceptions](https://dxr.mozilla.org/mozilla-central/source/toolkit/components/extensions/ExtensionStorage.jsm#119) so you'll probably have to periodically get the entire saved data and check its serialized length (for example 5MB). – wOxxOm Nov 12 '16 at 11:30

1 Answers1

1

Here is the beginnings of something you can use:

browser.storage.local.get(null)
    .then(store => {
            var bytes = 0;
            for (var p in store) {
                var entry = store[p];
                switch (typeof(p)) {
                    case 'number':
                        bytes += 8;
                        break;
                    case 'boolean':
                        bytes += 4;
                        break;
                    case 'string':
                        bytes += (entry.length * 2);
                        break;
                    case 'undefined':
                        bytes += 0;
                        break;
                    case 'object':
                        if (entry === null) {
                            bytes += 0;
                        } else {
                            if (entry.byteLength) {
                                bytes += entry.byteLength;
                            } else if (entry.buffer) {
                                bytes += entry.buffer.byteLength;
                            } else {
                                // todo: recrusively run this on all entries
                            }
                        }
                        break;
                    case 'array':
                        // todo: recursively run this on all elements
                        break;
                    default:
                        if (
                        }
                }
            });
        .catch(ex => console.warn('run borwser.storage.local.get again as it hit error, ex:', ex));

solutions here provide some recursive things - https://stackoverflow.com/a/6351386/1828637

Community
  • 1
  • 1
Noitidart
  • 35,443
  • 37
  • 154
  • 323
  • Thank you, I already got some script but I will compare both. Does your script have a license? – Julius S. Nov 13 '16 at 07:06
  • @JuliusS. - I just wrote it up, no liscence, just steal it and go :) I did it in a few minutes as I was replying to this, please touch it up and share here what you do. – Noitidart Nov 13 '16 at 17:27