{"id":13837637,"url":"https://github.com/onikienko/use-chrome-storage","last_synced_at":"2025-05-16T17:06:30.118Z","repository":{"id":36980796,"uuid":"341270073","full_name":"onikienko/use-chrome-storage","owner":"onikienko","description":"React hooks for chrome.storage. You can use it for keeping global state in chrome extensions.","archived":false,"fork":false,"pushed_at":"2025-05-10T02:06:21.000Z","size":16428,"stargazers_count":98,"open_issues_count":17,"forks_count":11,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-05-10T03:19:20.841Z","etag":null,"topics":["chrome-extensions","react","reacthook","web-extension"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/use-chrome-storage","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/onikienko.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-02-22T16:49:32.000Z","updated_at":"2025-05-10T02:04:56.000Z","dependencies_parsed_at":"2023-11-16T23:54:35.509Z","dependency_job_id":"886de6da-4c9d-42fc-b237-31680d385798","html_url":"https://github.com/onikienko/use-chrome-storage","commit_stats":{"total_commits":470,"total_committers":12,"mean_commits":"39.166666666666664","dds":"0.26595744680851063","last_synced_commit":"61236f05cde00231934e76fe7ca46a112100555e"},"previous_names":[],"tags_count":24,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/onikienko%2Fuse-chrome-storage","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/onikienko%2Fuse-chrome-storage/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/onikienko%2Fuse-chrome-storage/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/onikienko%2Fuse-chrome-storage/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/onikienko","download_url":"https://codeload.github.com/onikienko/use-chrome-storage/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254573588,"owners_count":22093731,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chrome-extensions","react","reacthook","web-extension"],"created_at":"2024-08-04T15:01:18.086Z","updated_at":"2025-05-16T17:06:30.067Z","avatar_url":"https://github.com/onikienko.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# use-chrome-storage\n\n☝️ This package is for usage in Chrome (and Chromium-based) Extensions, but it should work with Firefox extensions too.\n\nCustom React hooks for `chrome.storage.` You may use it to keep the global persisted state in Chrome Extensions.\n\n**Note:** Since it's a React hook, it may be used only in the React context.\nSo it's impossible to use this package in the background service worker.\n\n- Simplify work with `chrome.storage`\n- Supports `chrome.storage.local`, `chrome.storage.sync`, and `chrome.storage.session`\n- Can be used as persisted state available in different extension's contexts (content script, popup, options page)\n- Listen for `chrome.storage` changes and keep the local state updated\n\n## Install\n\n```bash\nnpm i use-chrome-storage\n```\n\n## Usage\n\nThis package requires the storage permission in manifest.json:\n\n```json\n{\n    \"name\": \"My Extension\",\n    \"permissions\": [\n        \"storage\"\n    ]\n}\n```\n\nFor usage with chrome.storage.**local** use `useChromeStorageLocal` hook. For chrome.storage.**sync**\nuse `useChromeStorageSync` hook. Use `useChromeStorageSession` for chrome.storage.**session**\n\n### Usage of useChromeStorage\n\n```javascript\nimport React from 'react';\nimport {useChromeStorageLocal} from 'use-chrome-storage';\n\n\nconst LocalCounter = () =\u003e {\n    // If you need to state be preserved in `chrome.storage.sync` use useChromeStorageSync\n    // for `chrome.storage.session` use useChromeStorageSession\n    const [value, setValue, isPersistent, error, isInitialStateResolved] = useChromeStorageLocal('counterLocal', 0);\n    return (\n            \u003cdiv\u003e\n                \u003cbutton\n                        onClick={() =\u003e {\n                            setValue(prev =\u003e (prev + 1));\n                        }}\n                \u003e\n                    Increment in Local Storage\n                \u003c/button\u003e\n                \u003cdiv\u003eValue: {value}\u003c/div\u003e\n                \u003cdiv\u003ePersisted in chrome.storage.local: {isPersistent.toString()}\u003c/div\u003e\n                \u003cdiv\u003eError: {error}\u003c/div\u003e\n                \u003cdiv\u003eIs state from chrome.storage already loaded? - {isInitialStateResolved.toString()}\u003c/div\u003e\n            \u003c/div\u003e\n    );\n};\n```\n\n### Usage of createChromeStorageStateHook\n\nIf you want to use the same `key` in different components in different extension parts in the React context (like in PopUp,\ncontent scripts,\n) you need to use `createChromeStorageStateHookLocal`(for chrome.storage.**local**),\n`createChromeStorageStateHookSync` (for chrome.storage.**sync**)\nand `createChromeStorageStateHookSession` (for chrome.storage.**session**).\n\nInitialize storage:\n\n```javascript\n// common/useSettingsStore.js\nimport {createChromeStorageStateHookLocal} from 'use-chrome-storage';\n\n\nconst SETTINGS_KEY = 'settings';\nconst INITIAL_VALUE = {\n    showAvatar: true,\n    showHistory: false,\n};\n\nexport const useSettingsStore = createChromeStorageStateHookLocal(SETTINGS_KEY, INITIAL_VALUE);\n```\n\nUse `useSettingsStore` on the options page:\n\n```javascript\n// options.js\nimport React from 'react';\nimport {useSettingsStore} from './common/useSettingsStore';\n\n\nconst Options = () =\u003e {\n    const [settings, setSettings, isPersistent, error, isInitialStateResolved] = useSettingsStore();\n\n    const handleChange = event =\u003e {\n        setSettings(prevState =\u003e {\n            return {\n                ...prevState,\n                [event.target.name]: event.target.checked\n            };\n        });\n    };\n\n    return (\n            \u003cdiv\u003e\n                \u003clabel\u003e\n                    \u003cinput\n                            type=\"checkbox\"\n                            name=\"showAvatar\"\n                            checked={settings.showAvatar}\n                            onChange={handleChange}\n                    /\u003e\n                    \u003cspan\u003eShow Avatar\u003c/span\u003e\n                \u003c/label\u003e\n                \u003clabel\u003e\n                    \u003cinput\n                            type=\"checkbox\"\n                            name=\"showHistory\"\n                            checked={settings.showHistory}\n                            onChange={handleChange}\n                    /\u003e\n                    \u003cspan\u003eShow History\u003c/span\u003e\n                \u003c/label\u003e\n                {isInitialStateResolved \u0026\u0026 \u003cdiv\u003eInitial state from \"chrome.storage\" is loaded\u003c/div\u003e}\n                {!isPersistent \u0026\u0026 \u003cdiv\u003eError writing to the chrome.storage: {error}\u003c/div\u003e}\n            \u003c/div\u003e\n    );\n};\n```\n\nOr from the content script:\n\n```javascript\n// contentScript.js\nimport React from 'react';\nimport Avatar from './common/Avatar';\nimport History from './common/History';\nimport {useSettingsStore} from './common/useSettingsStore';\n\n\nconst Card = () =\u003e {\n    const [settings] = useSettingsStore();\n\n    return (\n            \u003cdiv\u003e\n                {settings.showAvatar \u0026\u0026 \u003cAvatar/\u003e}\n                {settings.showHistory \u0026\u0026 \u003cHistory/\u003e}\n            \u003c/div\u003e\n    );\n};\n```\n\nIn the same way, you may use it for PopUp.\n\n### Initial Value flow\n\nSay we have the next hook:\n\n```javascript\nconst [value, setValue, isPersistent, error, isInitialStateResolved] = useChromeStorageLocal('counterLocal', 1);\n```\n\nSay in the `chrome.storage.local` we already have: `counterLocal: 10`.\n\nChanges of `value`:\n\n1. `value` is 1 (`initialValue` set in the hook)\n2. `useChromeStorageLocal` calls to Chrome API (this API is async) to get the value of `counterLocal`.\n\n- `value` changes to *10*\n- `isInitialStateResolved` changes to `true` indicating that `value` synchronized with data saved in `chrome.storage`\n\n### Usage with `chrome.storage.session`\n\n`useChromeStorageSession` and `createChromeStorageStateHookSessin` use `chrome.storage.session` to persist state.\nBy default, it's not exposed to content scripts,\nbut this behavior can be changed by calling `chrome.storage.session.setAccessLevel('TRUSTED_AND_UNTRUSTED_CONTEXTS')`\n(call it from the background script).\nhttps://developer.chrome.com/docs/extensions/reference/storage/#method-StorageArea-setAccessLevel\n\n### Clearing or removing storage items\n\nSuppose you want to reset all your stored items back to their initial values. \n\nYou could, for example, use `chrome.storage.local.clear()` (or their 'session', 'sync' counterparts) to clear the entire storage.  \nAlternatively, you can use `chrome.storage.local.remove(key)` to remove a specific storage item.\n\nThis will trigger a sync event in your `useChromeStorage[Local|Session|Sync]` hooks, setting them back to their _initial value_.\n\n## API\n\n### useChromeStorageLocal(key, initialValue?)\n\nThe state will be persisted in `chrome.storage.local` (and updated from `chrome.storage.local` if it was updated in other\ncontexts). If you want to use this hook in more than one place, use `createChromeStorageStateHookLocal`.\n\n- `key: string` - The key used in `chrome.storage.local`\n- `initialValue: any = undefined` - value which will be used if `chrome.storage.local` has no stored value yet or when a stored item is removed (unset)\n\n#### Returns\n\n`[value, setValue, isPersistent, error, isInitialStateResolved]`\n\n- `value: any` - stateful value like first one returned from `React.useState()`\n- `setValue: function` - function to update `value` like second one returned from `React.useState()`\n- `isPersistent: boolean` - Will be `true` if data is persisted in `chrome.storage.local`. In case of error\n  during `chrome.storage.local.get` or `chrome.storage.local.set` value will be stored in memory only and `isPersistent`\n  will be set to `false`\n- `error: string` - If `isPersistent` is `true` will contain empty string. Otherwise, will contain error returned\n  by `chrome.runtime.lastError`.\n- `isInitialStateResolved: boolean` - will set to `true` once `initialValue` will be replaced with stored in\n  chrome.storage\n\n### useChromeStorageSync(key, initialValue?)\n\nSimilar to `useChromeStorageLocal` but will use `chrome.storage.sync`. State will be persisted\nin `chrome.storage.sync` (and updated from `chrome.storage.sync` if it was updated in other contexts). If you want to\nuse this hook in more than one place, use `createChromeStorageStateHookSync`.\n\n- `key: string` - The key used in `chrome.storage.sync`\n- `initialValue: any = undefined` - value which will be used if `chrome.storage.sync` has no stored value yet\n\n#### Returns\n\n`[value, setValue, isPersistent, error]`\n\n- `value: any` - stateful value like the first one returned from `React.useState()`\n- `setValue: function` - function to update `value` like the second one returned from `React.useState()`\n- `isPersistent: boolean` - Will be `true` if data is persisted in `chrome.storage.sync`. In case of an error\n  during `chrome.storage.local.get` or `chrome.storage.local.set` value will be stored in memory only and `isPersistent`\n  will be set to `false`\n- `error: string` - If `isPersistent` is `true` will contain empty string. Otherwise, will contain error returned\n  by `chrome.runtime.lastError`.\n- `isInitialStateResolved: boolean` - will set to `true` once `initialValue` will be replaced with stored in\n  chrome.storage\n\n### useChromeStorageSession(key, initialValue?)\n\nSimilar to `useChromeStorageLocal` but will use `chrome.storage.session`. State will be persisted\nin `chrome.storage.session` (and updated from `chrome.storage.session` if it was updated in other contexts). If you want\nto use this hook in more than one place, use `createChromeStorageStateHookSession`.\n\n- `key: string` - The key used in `chrome.storage.session`\n- `initialValue: any = undefined` - value which will be used if `chrome.storage.session` has no stored value yet\n\n#### Returns\n\n`[value, setValue, isPersistent, error]`\n\n- `value: any` - stateful value like the first one returned from `React.useState()`\n- `setValue: function` - function to update `value` like the second one returned from `React.useState()`\n- `isPersistent: boolean` - Will be `true` if data is persisted in `chrome.storage.session`. In case of an error\n  during `chrome.storage.session.get` or `chrome.storage.session.set` value will be stored in memory only\n  and `isPersistent` will be set to `false`\n- `error: string` - If `isPersistent` is `true` will contain empty string. Otherwise, will contain an error returned\n  by `chrome.runtime.lastError`.\n- `isInitialStateResolved: boolean` - will set to `true` once `initialValue` will be replaced with stored in\n  `chrome.storage.session`\n\n### createChromeStorageStateHookLocal(key, initialValue?)\n\nIn case you want to use the same `key` in different components/extension contexts you could create the state hook which can\nbe used across the extension. See [example](#usage-of-createchromestoragestateHook). The state will be persisted\nin `chrome.storage.local`.\n\n- `key: string` - The key used in `chrome.storage.local`\n- `initialValue: any = undefined` - value which will be used if `chrome.storage.local` has no stored value yet\n\n### Returns\n\n`function(): [any, (value: any) =\u003e void, boolean, string, boolean]` - `useChromeStorageLocal` hook which may be used\nacross\nextension's components/pages\n\n### createChromeStorageStateHookSync(key, initialValue?)\n\nSimilar to `createChromeStorageStateHookLocal` but uses `chrome.storage.sync`. In case you want to use the same `key` in\ndifferent components/extension contexts you could create a state hook that can be used across the extension.\nSee [example](#usage-of-createchromestoragestateHook) and replace with `createChromeStorageStateHookSync`. State will be\npersisted in `chrome.storage.sync`.\n\n- `key: string` - The key used in `chrome.storage.sync`\n- `initialValue: any = undefined` - value which will be used if `chrome.storage.sync` has no stored value yet\n\n### Returns\n\n`function(): [any, (value: any) =\u003e void, boolean, string, boolean]` - `useChromeStorageSync` hook which may be used\nacross extension's components/pages\n\n### createChromeStorageStateHookSession(key, initialValue?)\n\nSimilar to `createChromeStorageStateHookLocal` but uses `chrome.storage.session`. In case you want to use the same `key` in\ndifferent components/extension contexts, you could create a state hook that can be used across extension.\nSee [example](#usage-of-createchromestoragestateHook) and replace with `createChromeStorageStateHookSession`. State will\nbe persisted in `chrome.storage.session`.\n\n- `key: string` - The key used in `chrome.storage.session`\n- `initialValue: any = undefined` - value which will be used if `chrome.storage.session` has no stored value yet\n\n### Returns\n\n`function(): [any, (value: any) =\u003e void, boolean, string, boolean]` - `useChromeStorageSession` hook which may be used\nacross extension's components/pages\n\n## Thanks to\n\n[use-local-storage-state](https://github.com/astoilkov/use-local-storage-state) for inspiration\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fonikienko%2Fuse-chrome-storage","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fonikienko%2Fuse-chrome-storage","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fonikienko%2Fuse-chrome-storage/lists"}