- Notifications
You must be signed in to change notification settings - Fork1
📪 Nifty service worker/client message utility
License
sdgluck/msgr
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Nifty service worker/client message utility
Made with ❤ at@outlandish
Makes communication between a client and service worker super easy...
- Send messages from client to worker and vice-versa
- Accommodates complex communications with a simple API
- Easily respond to any message
- Receive one-off responses to messages
To see it being used in the wild, check out the source code offetch-sync
.
Client
// ES6importmsgrfrom'msgr'// CommonJSvarmsgr=require('msgr')// RequireJSdefine(['msgr'],function(msgr){/*...*/})
<!-- Script, available as `window.msgr` --><scriptsrc="/node_modules/msgr/index.js"></script>
Worker
If you are bundling your SW then you can use the Import methods above.
Otherwise...
// importScriptsimportScripts('/node_modules/msgr/index.js')
Client:msgr.client()
Pass in reference to the worker and a collection of message handlers:
constrecipient=navigator.serviceWorker.controllerconstchannel=msgr.client(recipient,{// Predefined message handlersSAY_HELLO:(data)=>console.log('Hello, '+data)//=> 'Hello, World!'})// Send something "unknown" to the worker.// Notice it does not have a tag.channel.send({username:'Flanders',location:'Springfield'})// Send a "known" message to the workerchannel.send('CACHE_ASSET','/cat.gif').then(function(message){console.log(message)//=> 'Caching complete!'})
Worker:msgr.worker()
On the worker you just pass in your message handlers:
constchannel=msgr.worker({CACHE_ASSET:(url,respond)=>{cache(url).then(function(){respond('Caching complete!')})}})channel.receive(function(data){// Do something with an "unknown" message// that does not have a predefined handler.console.log(data)//=> { username: 'Flanders', ... }})// Send something "known" to the client using a tag.channel.send('SAY_HELLO','World!')
Anonymous, data-only message:
channel.send({requestId:'123'})
Type-only message:
channel.send('RE_CACHE')
Typed message with data:
channel.send('RE_CACHE',{assetUrl:'/cat.gif'})
The API for receiving messages is the same for both the worker and client.
Anonymous, data-only message:
channel.receive((data)=>{console.log(data.requestId)//=> '123'})
Type-only message:
msgr.client({RE_CACHE:(data,respond)=>{console.log(data)//=> null}})
Typed message with data:
msgr.client({RE_CACHE:(data,respond)=>{console.log(data.assetUrl)//=> '/cat.gif'}})
Initialise amsgr
client.
- serviceWorker {ServiceWorkerRegistration} Worker that will receive messages sent via channel
- handlers {Object} An object of message type/handler mappings
Returns a Channel. See theChannel API Docs for more details.
Example:
msgr.client(navigator.serviceWorker.controller,{NOTIFY:function(respond){newNotification('You have a notification!')respond('GOT_THE_NOTIFICATION')}})
Initialise amsgr
worker.
- handlers {Object} An object of message type/handler mappings
Returns a Channel. See theChannel API Docs for more details.
Example:
msgr.worker({NOTIFY:function(respond){newNotification('You have a notification!')respond('GOT_THE_NOTIFICATION')}})
Register a handler to be called when the channel is opened between client and worker.
- handler {Function} The ready handler
Although you can register ready handlers, you can send messages before the channel is open usingchannel.send()
and these will be queued and sent as soon as the channel is ready.
Example:
channel.ready(function(){application.start()})
Send a message through the channel to the worker/client.
- [type] {String}(optional) The message type
- data {Any} The message data (it will be JSON.stringify'd)
Returns a Message. See theMessage API Docs for more details.
If called before the channel is ready the message will be queued and sent as soon as the channel is open.
Example:
// Typed message, will invoke registered type handlerschannel.send('NOTIFY_USER')// Typed message with data, will invoke registered type handlerschannel.send('NOTIFY_USER',{message:'Update complete'})// Anonymous, will invoke `receive` handlerschannel.send('This is the untagged data')
Handle an "unknown" message that is not tagged.
- handler {Function} The message handler
The handler receives two arguments: thedata
of the message and arespond
function.
Example:
channel.receive(function(data,respond){console.log('Got some unknown data: '+data)})
Register a handler to receive the response to a message.
- handler {Function} Response handler
Example:
// In client message handlersmsgr({NOTIFY_USER:function(data,respond){newNotification('Job '+data.id+' was completed')respond('From worker: job deleted')// ACK}})// In workerchannel.send('NOTIFY_USER',{id:1337}).then((data)=>{console.log(data)//=> 'From worker: job deleted'})
Send a response to a received message.
This function is passed as the second argument to both "known" and "unknown" message handlers.
- [data] {Any}(optional) The data to respond to the message with
All pull requests and issues welcome!
If you're not sure how, check out Kent C. Dodds'great video tutorials on egghead.io!
msgr
was created bySam Gluck and is released under the MIT license.