Last active
December 23, 2015 01:29
-
-
Save gryzzly/6560822 to your computer and use it in GitHub Desktop.
tabTalk
This file contains 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(root, mod) { | |
if (typeof exports == "object" && typeof module == "object") return mod(exports); // CommonJS | |
if (typeof define == "function" && define.amd) return define(["exports"], mod); // AMD | |
mod(root.tabTalk || (root.tabTalk = {})); // Plain browser env | |
})(this, function(exports) {"use strict"; | |
var | |
win = window | |
, storage = win.localStorage | |
, prefix = 'tab_' | |
, instance = prefix + date.now() // identify this tab | |
, matcher = new RegExp(prefix + '\\d{13}$') | |
, callbacks = [] | |
; | |
exports.talk = talk; | |
exports.listen = listen; | |
win.addEventListener('storage', onStorageHandler); | |
function onStorageHandler (event) { | |
// event.key String the named key that changed | |
// event.oldValue and event.newValue are available | |
// event.url the page that caused the value to change | |
var key = event.key; | |
// event's coming from tabTalk and it's not the current tab | |
if (key !== instance && matcher.test(key)) { | |
if (callbacks.length) { | |
callbacks.forEach(function (fn) { | |
fn({ key: key, message: event.newValue }); | |
}); | |
} | |
} | |
function talk (message) { | |
localStorage[instance] = message; | |
} | |
function listen (fn) { | |
callbacks.push(fn); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment