- Notifications
You must be signed in to change notification settings - Fork183
A set of utilities for building Redux applications in Web Extensions.
License
tshaddix/webext-redux
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
A set of utilities for building Redux applications in web extensions. This package was originally namedreact-chrome-redux.
This package is available onnpm:
npm install webext-reduxwebext-redux allows you to build your Web Extension like a Redux-powered webapp. The background page holds the Redux store, while Popovers and Content-Scripts act as UI Components, passing actions and state updates between themselves and the background store. At the end of the day, you have a single source of truth (your Redux store) that describes the entire state of your extension.
All UI Components follow the same basic flow:
- UI Component dispatches action to a Proxy Store.
- Proxy Store passes action to background script.
- Redux Store on the background script updates its state and sends it back to UI Component.
- UI Component is updated with updated state.
Basic Usage (full docs here)
As described in theintroduction, there are two pieces to a basic implementation of this package.
// popover.jsimportReactfrom'react';import{render}from'react-dom';import{Provider}from'react-redux';import{Store}from'webext-redux';importAppfrom'./components/app/App';conststore=newStore();// wait for the store to connect to the background pagestore.ready().then(()=>{// The store implements the same interface as Redux's store// so you can use tools like `react-redux` no problem!render(<Providerstore={store}><App/></Provider>,document.getElementById('app'));});
// background.jsimport{createWrapStore}from'webext-redux';conststore;// a normal Redux storeconstwrapStore=createWrapStore()wrapStore(store);
That's it! The dispatches called from UI component will find their way to the background page no problem. The new state from your background page will make sure to find its way back to the UI components.
Note
createWrapStore() ensures webext-redux can handle events when the service worker restarts. It must be called statically in the global scope of the service worker. In other words, it shouldn't be nested in async functions, just likeany other Chrome event listeners.
Just like a regular Redux store, you can apply Redux middlewares to the Proxy store by using the library provided applyMiddleware function. This can be useful for doing things such as dispatching thunks to handle async control flow.
// content.jsimport{Store,applyMiddleware}from'webext-redux';importthunkMiddlewarefrom'redux-thunk';// Proxy storeconststore=newStore();// Apply middleware to proxy storeconstmiddleware=[thunkMiddleware];conststoreWithMiddleware=applyMiddleware(store, ...middleware);// You can now dispatch a function from the proxy storestoreWithMiddleware.dispatch((dispatch,getState)=>{// Regular dispatches will still be routed to the backgrounddispatch({type:'start-async-action'});setTimeout(()=>{dispatch({type:'complete-async-action'});},0);});
4. Optional: Implement actions whose logic only happens in the background script (we call them aliases)
Sometimes you'll want to make sure the logic of your action creators happen in the background script. In this case, you will want to create an alias so that the alias is proxied from the UI component and the action creator logic executes in the background script.
// background.jsimport{applyMiddleware,createStore}from'redux';import{alias}from'webext-redux';constaliases={// this key is the name of the action to proxy, the value is the action// creator that gets executed when the proxied action is received in the// background'user-clicked-alias':()=>{// this call can only be made in the background scriptbrowser.notifications.create(...);};};conststore=createStore(rootReducer,applyMiddleware(alias(aliases)));
// content.jsimport{Component}from'react';conststore= ...;// a proxy storeclassContentAppextendsComponent{render(){return(<inputtype="button"onClick={this.dispatchClickedAlias.bind(this)}/>);}dispatchClickedAlias(){store.dispatch({type:'user-clicked-alias'});}}
There are probably going to be times where you are going to want to know who sent you a message. For example, maybe you have a UI Component that lives in a tab and you want to have it send information to a store that is managed by the background script and you want your background script to know which tab sent the information to it. You can retrieve this information by using the_sender property of the action. Let's look at an example of what this would look like.
// actions.jsexportconstMY_ACTION='MY_ACTION';exportfunctionmyAction(data){return{type:MY_ACTION,data:data,};}
// reducer.jsimport{MY_ACTION}from'actions.js';exportfunctionrootReducer(state= ...,action){switch(action.type){caseMY_ACTION:returnObject.assign({}, ...state,{lastTabId:action._sender.tab.id});default:returnstate;}}
No changes are required to your actions, webext-redux automatically adds this information for you when you use a wrapped store.
Contrary to regular Redux,all dispatches are asynchronous and return aPromise.It is inevitable since proxy stores and the main store communicate via browser messaging, which is inherently asynchronous.
In pure Redux, dispatches are synchronous(which may not be true with some middlewares such asredux-thunk).
Consider this piece of code:
store.dispatch({type:MODIFY_FOO_BAR,value:'new value'});console.log(store.getState().fooBar);
You can rely thatconsole.log in the code above will display the modified value.
Inwebext-redux on the Proxy Store side you will need toexplicitly wait for the dispatch to complete:
store.dispatch({type:MODIFY_FOO_BAR,value:'new value'}).then(()=>console.log(store.getState().fooBar));
or, using async/await syntax:
awaitstore.dispatch({type:MODIFY_FOO_BAR,value:'new value'});console.log(store.getState().fooBar);
This case is relatively rare.
On the Proxy Store side, React component updates withwebext-reduxare more likely to take place after a dispatch is started and before it completes.
While the code below might work (luckily?) in classical Redux,it does not anymore since the component has been updated before thedeletePost is fully completedandpost object is not accessible anymore in the promise handler:
classPostRemovePanelextendsReact.Component{(...)handleRemoveButtonClicked(){this.props.deletePost(this.props.post).then(()=>{this.setState({message:`Post titled${this.props.post.title} has just been deleted`});});}}
On the other hand, this piece of code is safe:
handleRemoveButtonClicked(){constpost=this.props.post;this.props.deletePost(post);.then(()=>{this.setState({message:`Post titled${post.title} has just been deleted`});});}}
If you spot any more surprises that are worth watching out for, make sure to let us know!
You may wish to implement custom serialization and deserialization logic for communication between the background store and your proxy store(s). Web Extension's message passing (which is used to implement this library) automatically serializes messages when they are sent and deserializes them when they are received. In the case that you have non-JSON-ifiable information in your Redux state, like a circular reference or aDate object, you will lose information between the background store and the proxy store(s). To manage this, bothwrapStore andStore acceptserializer anddeserializer options. These should be functions that take a single parameter, the payload of a message, and return a serialized and deserialized form, respectively. Theserializer function will be called every time a message is sent, and thedeserializer function will be called every time a message is received. Note that, in addition to state updates, action creators being passed from your content script(s) to your background page will be serialized and deserialized as well.
For example, consider the followingstate in your background page:
{todos:[{id:1,text:'Write a Web extension',created:newDate(2018,0,1)}]}
With no custom serialization, thestate in your proxy store will look like this:
{todos:[{id:1,text:'Write a Web extension',created:{}}]}
As you can see, Web Extension's message passing has caused your date to disappear. You can pass a customserializer anddeserializer to bothwrapStore andStore to make sure your dates get preserved:
// background.jsimport{createWrapStore}from'webext-redux';constwrapStore=createWrapStore();conststore;// a normal Redux storewrapStore(store,{serializer:payload=>JSON.stringify(payload,dateReplacer),deserializer:payload=>JSON.parse(payload,dateReviver)});
// content.jsimport{Store}from'webext-redux';conststore=newStore({serializer:payload=>JSON.stringify(payload,dateReplacer),deserializer:payload=>JSON.parse(payload,dateReviver)});
In this example,dateReplacer anddateReviver are a custom JSONreplacer andreviver function, respectively. They are defined as such:
functiondateReplacer(key,value){// Put a custom flag on dates instead of relying on JSON's native// stringification, which would force us to use a regex on the other endreturnthis[key]instanceofDate ?{"_RECOVER_DATE":this[key].getTime()} :value};functiondateReviver(key,value){// Look for the custom flag and revive the datereturnvalue&&value["_RECOVER_DATE"] ?newDate(value["_RECOVER_DATE"]) :value};conststringified=JSON.stringify(state,dateReplacer)//"{"todos":[{"id":1,"text":"Write a Web extension","created":{"_RECOVER_DATE":1514793600000}}]}"JSON.parse(stringified,dateReviver)// {todos: [{ id: 1, text: 'Write a Web extension', created: new Date(2018, 0, 1) }]}
On each state update,webext-redux generates a patch based on the difference between the old state and the new state. The patch is sent to each proxy store, where it is used to update the proxy store's state. This is more efficient than sending the entire state to each proxy store on every update.If you find that the default patching behavior is not sufficient, you can fine-tunewebext-redux using custom diffing and patching strategies.
By default,webext-redux uses a shallow diffing strategy to generate patches. If the identity of any of the store's top-level keys changes, their values are patched wholesale. Most of the time, this strategy will work just fine. However, in cases where a store's state is highly nested, or where many items are stored by key under a single slice of state, it can start to affect performance. Consider, for example, the followingstate:
{items:{"a":{ ...},"b":{ ...},"c":{ ...},"d":{ ...},// ...},// ...}
If any of the individual keys understate.items is updated,state.items will become a new object (by standard Redux convention). As a result, the default diffing strategy will send then entirestate.items object to every proxy store for patching. Since this involves serialization and deserialization of the entire object, having large objects - or many proxy stores - can create a noticeable slowdown. To mitigate this,webext-redux also provides a deep diffing strategy, which will traverse down the state tree until it reaches non-object values, keeping track of only the updated keys at each level of state. So, for the example above, if the object understate.items.b is updated, the patch will only contain those keys understate.items.b whose values actually changed. The deep diffing strategy can be used like so:
// background.jsimport{createWrapStore}from'webext-redux';importdeepDifffrom'webext-redux/lib/strategies/deepDiff/diff';constwrapStore=createWrapStore();conststore;// a normal Redux storewrapStore(store,{diffStrategy:deepDiff});
// content.jsimport{Store}from'webext-redux';importpatchDeepDifffrom'webext-redux/lib/strategies/deepDiff/patch';conststore=newStore({patchStrategy:patchDeepDiff});
Note that the deep diffing strategy currently diffs arrays shallowly, and patches item changes based on typed equality.
webext-redux also provides amakeDiff function to customize the deep diffing strategy. It takes ashouldContinue function, which is called during diffing just after each state tree traversal, and should return a boolean indicating whether or not to continue down the tree, or to just treat the current object as a value. It is called with the old state, the new state, and the current position in the state tree (provided as a list of keys so far). Continuing the example from above, say you wanted to treat all of the individual items understate.items as values, rather than traversing into each one to compare its properties:
// background.jsimport{createWrapStore}from'webext-redux';importmakeDifffrom'webext-redux/lib/strategies/deepDiff/makeDiff';constwrapStore=createWrapStore();conststore;// a normal Redux storeconstshouldContinue=(oldState,newState,context)=>{// If we've just traversed into a key under state.items,// stop traversing down the tree and treat this as a changed value.if(context.length===2&&context[0]==='items'){returnfalse;}// Otherwise, continue down the tree.returntrue;}// Make the custom deep diff using the shouldContinue functionconstcustomDeepDiff=makeDiff(shouldContinue);wrapStore(store,{diffStrategy:customDeepDiff// Use the custom deep diff});
Now, for each key understate.items,webext-redux will treat it as a value and patch it wholesale, rather than comparing each of its individual properties.
AshouldContinue function of the form(oldObj, newObj, context) => context.length === 0 is equivalent towebext-redux's default shallow diffing strategy, since it will only check the top-level keys (whencontext is an empty list) and treat everything under them as changed values.
You can also provide your own diffing and patching strategies, using thediffStrategy parameter inwrapStore and thepatchStrategy parameter inStore, respectively. A diffing strategy should be a function that takes two arguments - the old state and the new state - and returns a patch, which can be of any form. A patch strategy is a function that takes two arguments - the old state and a patch - and returns the new state.When using a custom diffing and patching strategy, you are responsible for making sure that they function as expected; that is, thatpatchStrategy(oldState, diffStrategy(oldState, newState)) is equal tonewState.
Aside from being able to fine-tunewebext-redux's performance, custom diffing and patching strategies allow you to usewebext-redux with Redux stores whose states are not vanilla Javascript objects. For example, you could implement diffing and patching strategies - along with corresponding custom serialization and deserialization functions - that allow you to handleImmutable.js collections.
Usingwebext-redux in your project? We'd love to hear about it! Justopen an issue and let us know.
About
A set of utilities for building Redux applications in Web Extensions.
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.





