Skip to content

Instantly share code, notes, and snippets.

@black-black-cat
Last active December 22, 2017 16:30
Show Gist options
  • Select an option

  • Save black-black-cat/bb33c1fffd76a4b7faf83e4273e94fc8 to your computer and use it in GitHub Desktop.

Select an option

Save black-black-cat/bb33c1fffd76a4b7faf83e4273e94fc8 to your computer and use it in GitHub Desktop.
跨浏览器标签通信
;(function (root, factory) {
root.CrossTab = factory()
}(window, function factory() {
var store = {
get: function (key) {
var strValue = localStorage.getItem(key)
var value
try {
value = JSON.parse(strValue)
} catch (err) {
value = strValue
}
return value
},
set: function (key, value) {
if (value === void 0) return
var strValue = JSON.stringify(value)
localStorage.setItem(key, strValue)
}
}
var CROSS_TAB = '__cross_tab__'
function _send(type, message) {
store.set(CROSS_TAB, {
type: type,
timeStamp: Date.now(),
message: message
})
}
function _on(type, func) {
var handlers = this.handlers
handlers[type] = handlers[type] == null ? [func] : handlers[type].concat(func)
}
function _init() {
var instance = this
window.addEventListener('storage', function (ev){
var self = this
var crossEvent = store.get( ev.key )
if (!crossEvent) return
if (ev.key != CROSS_TAB) return
var crossEventType = crossEvent.type
instance && instance.handlers[crossEventType]
&& instance.handlers[crossEventType].forEach(function (func) {
func && func.apply(self, [{
originEvent: ev,
data: crossEvent
}])
})
})
}
function CrossTab() {
if (!(this instanceof CrossTab)) {
return new CrossTab()
}
this.handlers = {}
this.init()
}
CrossTab.send = _send
CrossTab.prototype.init = _init
CrossTab.prototype.on = _on
CrossTab.prototype.send = _send
return CrossTab
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment