Skip to content

Instantly share code, notes, and snippets.

@gryzzly
Last active December 23, 2015 01:29
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 gryzzly/6560822 to your computer and use it in GitHub Desktop.
Save gryzzly/6560822 to your computer and use it in GitHub Desktop.
tabTalk
(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