Skip to content

Instantly share code, notes, and snippets.

@liranh85
Created June 29, 2019 11:17
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 liranh85/2e596acbf65dbf6527be6cd152d42523 to your computer and use it in GitHub Desktop.
Save liranh85/2e596acbf65dbf6527be6cd152d42523 to your computer and use it in GitHub Desktop.
A custom polyfill to BroadcastChannel, falling back on localStorage if not supported by the browser
(function BroadcastChannelPolyfill() {
if (!('BroadcastChannel' in window)) {
console.log('Using BroadcastChannel polyfill')
window.BroadcastChannel = function(name) {
this.channelName = name
this.onmessage = function() {}
var self = this
window.addEventListener("storage", function(event) {
if (event.key != 'message') {
// ignore other keys
return
}
var message = JSON.parse(event.newValue)
if (!message) {
// ignore empty msg or msg reset
return
}
if (message.channel === self.channelName) {
self.onmessage(message)
}
})
}
window.BroadcastChannel.prototype.postMessage = function(msg) {
localStorage.setItem('message', JSON.stringify({ channel: this.channelName, data: msg }))
localStorage.removeItem('message')
}
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment