Skip to content

Commit

Permalink
cross-browser storage usage
Browse files Browse the repository at this point in the history
  • Loading branch information
Claudiohbsantos committed Jul 28, 2022
1 parent aa24b9c commit f559bdf
Showing 1 changed file with 20 additions and 14 deletions.
34 changes: 20 additions & 14 deletions src/lib/userConfig.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,36 @@
const hardDefaults = {
iconPack: 'react',
iconSize: 'md',
extEnabled: true
extEnabled: true,
};

export const getConfig = (config, domain = window.location.hostname, useDefault = true) =>
chrome.storage.sync
.get({
// get custom domain config (if not getting default).
[`${domain !== 'default' ? domain : 'SKIP'}:${config}`]: null,
// also get user default as fallback
[`default:${config}`]: hardDefaults[config],
})
.then(
({ [`${domain}:${config}`]: value, [`default:${config}`]: fallback }) => value ?? (useDefault ? fallback : null)
new Promise((resolve) => {
chrome.storage.sync.get(
{
// get custom domain config (if not getting default).
[`${domain !== 'default' ? domain : 'SKIP'}:${config}`]: null,
// also get user default as fallback
[`default:${config}`]: hardDefaults[config],
},
({ [`${domain}:${config}`]: value, [`default:${config}`]: fallback }) =>
resolve(value ?? (useDefault ? fallback : null))
);
});

export const setConfig = (config, value, domain = window.location.hostname) =>
chrome.storage.sync.set({
[`${domain}:${config}`]: value,
});

export const clearConfig = (config, domain = window.location.hostname) =>
chrome.storage.sync.remove( `${domain}:${config}`);
new Promise((resolve) => {
chrome.storage.sync.remove(`${domain}:${config}`, resolve);
});

export const onConfigChange = (config, handler, domain = window.location.hostname) =>
chrome.storage.onChanged.addListener((changes) => {
changes[`${domain}:${config}`]?.newValue !== undefined && handler(changes[`${domain}:${config}`]?.newValue);
});
chrome.storage.onChanged.addListener(
(changes) =>
changes[`${domain}:${config}`]?.newValue !== undefined &&
handler(changes[`${domain}:${config}`]?.newValue)
);

0 comments on commit f559bdf

Please sign in to comment.