Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jonasfrey/b028ec154dd358c0b4b6373fcfa3ca24 to your computer and use it in GitHub Desktop.
Save jonasfrey/b028ec154dd358c0b4b6373fcfa3ca24 to your computer and use it in GitHub Desktop.
share javascript object between browser tabs (with localStorage, Proxy and BroadCast)
let o_bc_o_localstorage = false;
if("BroadcastChannel" in window){
o_bc_o_localstorage = new BroadcastChannel('o_localstorage');
}
let f_o_localstorage_from_json_parse = function(){
let o_localstorage = {}
let s_o_localstorage = localStorage.getItem('o_localstorage');
if(s_o_localstorage){
o_localstorage = JSON.parse(s_o_localstorage)
}
return o_localstorage
}
let o_localstorage = f_o_localstorage_from_json_parse();
let f_update_localstorage = function(){
if(o_bc_o_localstorage){
o_bc_o_localstorage.postMessage('update')
}
localStorage.setItem('o_localstorage', JSON.stringify(o_localstorage))
}
let f_o_proxied_recursive = function(o, f_set, f_get){
for(let s in o){
if(typeof o[s] == 'object'){
o[s] = f_o_proxied_recursive(o[s], f_set, f_get)
}
}
o = new Proxy(o, {set: f_set, get: f_get});
return o
}
let f_get = function(v_target, s_prop, v_receiver) {
return Reflect.get(...arguments);
}
let f_set = function(v_target, s_prop, v_receiver) {
console.log("setter called")
if(typeof v_receiver == 'object'){
v_receiver = f_o_proxied_recursive(v_receiver, f_set, f_get)
}
let o_res = Reflect.set(v_target, s_prop, v_receiver);
f_update_localstorage()
return o_res
}
let f_reproxy_o_localstorage = function(){
o_localstorage = f_o_localstorage_from_json_parse()
o_localstorage = f_o_proxied_recursive(o_localstorage, f_set, f_get)
}
if(o_bc_o_localstorage){
o_bc_o_localstorage.onmessage = function(){
console.log("reproxy")
f_reproxy_o_localstorage()
}
f_reproxy_o_localstorage()
}
if(!o_bc_o_localstorage){
let n_id = 0;
let f_recursive = function(){
n_id = window.requestAnimationFrame(f_recursive)
f_reproxy_o_localstorage()
}
n_id = window.requestAnimationFrame(f_recursive)
}
//tab1
o_localstorage.n = 420
o_localstorage.a = [1,2,3,4]
o_localstorage.o_s_o = {o_s_name_a_n:{a_1:[1,2,3], a_2:['a', 'b']}}
o_localstorage.o_s_o.o_s_name_a_n.a_1.push(420)
o_localstorage.o_s_o.o_s_name_a_n.a_2.push('fourtwenty')
//tab1
o_localstorage.o1={o2:{o3:{n:4}}}
//tab2
console.log(o_localstorage.o1.o2.o3.n) // 4
o_localstorage.o1.o2.o3.n = 5
//tab1
console.log(o_localstorage.o1.o2.o3.n) // 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment