chrome-utils
Some utils that help to build chrome extension. HAVE NO DEPENDENCIES.
Usage
$ npm i chrome-utils --save
// es6; // es5const store = store;
Api
store
chrome.storage
API is anti-human, for example, if you saved a non-plain object to store, {a: {b: 1, c: {d: 2}}}
, then how to directly get the value of d
from it?
One more question, if you have already save {a1: {b: 1}, a2: {c: 2}}
to store, then wanna update b
to 2
, then how to do it? If we use raw API like chrome.storage.sync.set({a1: {b: 2}})
, then we'll find a2
was totally disappeard!
Actually, by raw chrome.storage
API:
- you can only get the top key-value
- you can only get
a
but nota.b.d
. - if you wanna update a value in a object, you must get it from store first, then update the whole object, finally, save it to store.
WTF?
get & set
If target value exist, then auto to merge it
store;store; // usage examplestore;store; // {c: 1} store;store; // inject b, get {a: {b: 2, c: 1}}store; // directly get b, return 2 store;store; // update, get 3
listen
store; // listenerconst listener = key // the key you wanna to listen change callback;const listeners = listener1 listener2 listener3;
clear & remove
storeclear;store; // examplestore;store; // {b: 1, c: 2} store;// after removestore; // => {b: null, c: 2} store;// after removestore; // => null
storeAsync
Uses promises instead of callbacks. Plays well with async/await
.
; // with promisesstorestorestorestoreclear // with async/await { await store const b = await store console}
message
Compare with raw API chrome.runtime.onMessage
& chrome.runtime.sendMessage
, it:
- force user add
type
for each msg - if msg listener as a
type
key, it will only response to target type msg
send message
message; // msgconst msg = type // required data;
send msg to tabs
message;
register listener
message; // listenerconst listener = callback // required, type // not required, but if you use it, this listener will only listen same type msg;
i18n
get message
i18n;
Todo
- remove
merge
api - expire time for store
- test
- more use case