Welcome to mirror list, hosted at ThFree Co, Russian Federation.

accessor.js « utils « lib « javascripts « assets « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f7cdc564538ff9e4d8a3ac432bdd411c6b8894de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
function canAccessProperty(base, property) {
  let safe;

  try {
    safe = Boolean(base[property]);
  } catch (error) {
    safe = false;
  }

  return safe;
}

function canCallFunction(base, functionName, ...args) {
  let safe = true;

  try {
    base[functionName](...args);
  } catch (error) {
    safe = false;
  }

  return safe;
}

/**
 * Determines if `window.localStorage` is available and
 * can be written to and read from.
 *
 * Important: This is not a guarantee that
 * `localStorage.setItem` will work in all cases.
 *
 * `setItem` can still throw exceptions and should be
 * surrounded with a try/catch where used.
 *
 * See: https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem#exceptions
 */
function canUseLocalStorage() {
  let safe;

  const TEST_KEY = 'canUseLocalStorage';
  const TEST_VALUE = 'true';

  safe = canAccessProperty(window, 'localStorage');
  if (!safe) return safe;

  safe = canCallFunction(window.localStorage, 'setItem', TEST_KEY, TEST_VALUE);

  if (safe) window.localStorage.removeItem(TEST_KEY);

  return safe;
}

/**
 * Determines if `window.crypto` is available.
 */
function canUseCrypto() {
  return window.crypto?.subtle !== undefined;
}

const AccessorUtilities = {
  canUseLocalStorage,
  canUseCrypto,
};

export default AccessorUtilities;