changeset 83:caab77328b1c

js (common): added a method to check if local or session storage is available
author Goffi <goffi@goffi.org>
date Wed, 03 Jan 2018 01:12:16 +0100
parents 6ba0129a9a4e
children b2ef34e602cf
files default/static/common.js
diffstat 1 files changed, 49 insertions(+), 2 deletions(-) [+]
line wrap: on
line diff
--- a/default/static/common.js	Wed Jan 03 01:12:16 2018 +0100
+++ b/default/static/common.js	Wed Jan 03 01:12:16 2018 +0100
@@ -1,3 +1,48 @@
+var __session_storage_available;
+var __local_storage_available;
+
+function storageAvailable(type) {
+    /* check if session or local storage is available
+     *
+     * @param type(string): "session" or "storage"
+     * @return (boolean): true if requested storage is available
+     */
+    console.assert(type == 'session' || type == 'storage', "bad storage type (%s)", type);
+    const var_name = '__' + type + '_storage_available';
+    var available = window[var_name];
+    if (available === undefined) {
+        // test method from https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
+        var storage = window[type + 'Storage'];
+        try {
+            x = '__storage_test__';
+            storage.setItem(x, x);
+            storage.removeItem(x);
+            available = true;
+        }
+        catch(e) {
+            available = e instanceof DOMException && (
+                    // everything except Firefox
+                    e.code === 22 ||
+                    // Firefox
+                    e.code === 1014 ||
+                    // test name field too, because code might not be present
+                    // everything except Firefox
+                    e.name === 'QuotaExceededError' ||
+                    // Firefox
+                    e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
+                // acknowledge QuotaExceededError only if there's something already stored
+                storage.length !== 0;
+        }
+
+        if (!available) {
+            console.warn("%s storage not available", type);
+        }
+        window[var_name] = available;
+    }
+
+    return available;
+}
+
 function toggle_clicked_class_tag(tag_name, class_name='clicked') {
     for (let elt of document.getElementsByTagName(tag_name)) {
         elt.classList.toggle(class_name);
@@ -46,9 +91,11 @@
     /* toggle clicked, and fix max-height on transitionend
      *
      * needed to workaround transition issue with max-height:none
+     * inspired from https://css-tricks.com/using-css-transitions-auto-dimensions,
+     * thanks to Brandon Smith
      *
-     * inspired from https://css-tricks.com/using-css-transitions-auto-dimensions,
-     * thanks to Brandon Smith */
+     * @param arg: element to toggle (id as string, or element itself)
+     * */
     elt = get_elt(arg);
 
     if (!elt.classList.contains("clicked")) {