Skip to content

Instantly share code, notes, and snippets.

@rektide
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rektide/36c5ec5301fb17f37ea6 to your computer and use it in GitHub Desktop.
Save rektide/36c5ec5301fb17f37ea6 to your computer and use it in GitHub Desktop.
// a broadcast-channel-ification of https://github.com/mkruisselbrink/navigator-connect/issues/1#issuecomment-62989902
var discoveryService = new BroadcastChannel("discoveryservice");
// service discovery
var serviceChannelName = "appservice"
var notifyService = new BroadcastChannel(serviceChannelName);
setTimeout(function(){
discoveryService.postMessage({ service: "net.yoyodyne.Notify", channel: serviceChannelName });
},100)
// notify service
setTimeout(function(){
if (Math.random() < 0.5) notifyService.postMessage({notice:"notice"});
},1000);
// client
var discoveryConsumer = new BroadcastChannel("discoveryservice")
var discoverNotify = function(e) {
if(e.data && e.data.service === "net.yoyodyne.Notify" && e.data.channel) {
discoveryConsumer.removeListener(discoverNotify)
var notifyChannel = new BroadcastChannel(e.data.channel)
notifyChannel.addEventListener("message", function(f) {
console.log("Important message from " + f.origin + ": " + JSON.stringify(f.data))
})
}
})
discoveryConsumer.addEventListener("discoveryservice", discoverNotify)
// https://github.com/mkruisselbrink/navigator-connect/issues/1#issuecomment-62989902
// service worker:
self.onactivate = function(e) {
e.waitUntil(navigator.connect('https://rektide.com/discoveryservice/register').then(
function(port) {
port.postMessage({url: 'https://example.com/services/notify', action: 'com.rektide.Notify'});
}
));
};
// other event handlers...
// client code:
navigator.connect('https://rektide.com/discoveryservice/lookup').then(
function(discoveryPort) {
discoveryPort.postMessage({action: 'com.rektide.Notify'});
discoveryPort.onmessage = function(event) {
var services = event.data.services;
navigator.connect(services[0]).then(
function(port) {
// ....
}
);
};
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment