Created
June 29, 2019 11:17
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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