debian-mirror-gitlab/app/assets/javascripts/lib/utils/accessor.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

66 lines
1.3 KiB
JavaScript
Raw Normal View History

2021-11-11 11:23:49 +05:30
function canAccessProperty(base, property) {
2017-08-17 22:00:37 +05:30
let safe;
try {
2019-09-04 21:01:54 +05:30
safe = Boolean(base[property]);
2017-08-17 22:00:37 +05:30
} catch (error) {
safe = false;
}
return safe;
}
2021-11-11 11:23:49 +05:30
function canCallFunction(base, functionName, ...args) {
2017-08-17 22:00:37 +05:30
let safe = true;
try {
base[functionName](...args);
} catch (error) {
safe = false;
}
return safe;
}
2021-11-11 11:23:49 +05:30
/**
* 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() {
2017-08-17 22:00:37 +05:30
let safe;
2021-11-11 11:23:49 +05:30
const TEST_KEY = 'canUseLocalStorage';
2017-08-17 22:00:37 +05:30
const TEST_VALUE = 'true';
2021-11-11 11:23:49 +05:30
safe = canAccessProperty(window, 'localStorage');
2017-08-17 22:00:37 +05:30
if (!safe) return safe;
2021-11-11 11:23:49 +05:30
safe = canCallFunction(window.localStorage, 'setItem', TEST_KEY, TEST_VALUE);
2017-08-17 22:00:37 +05:30
if (safe) window.localStorage.removeItem(TEST_KEY);
return safe;
}
2022-05-07 20:08:51 +05:30
/**
* Determines if `window.crypto` is available.
*/
function canUseCrypto() {
return window.crypto?.subtle !== undefined;
}
2017-08-17 22:00:37 +05:30
const AccessorUtilities = {
2021-11-11 11:23:49 +05:30
canUseLocalStorage,
2022-05-07 20:08:51 +05:30
canUseCrypto,
2017-08-17 22:00:37 +05:30
};
export default AccessorUtilities;