Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect presence of other tabs / windows of same domain

If I have two (or more) tabs open at the same domain, is there a simple way to sense the presence of the other one, (so as to control what computations I do)? I understand there is a window.open() function, but I am not opening one window from another. Instead imagine a user goes with two tabs to mydomain.com.

I have started writing some code doing using HTML5 local storage, where I periodically leave messages and check messages, but this seems a bit convoluted.

like image 557
zenna Avatar asked Mar 06 '12 01:03

zenna


1 Answers

That is an interesting problem.

We can try around those api: postMessage, sessionStorage, localStorage, webRtc.


The BroadcastChannel suits very well:

BroadcastChannel allows scripts from the same origin but other browsing contexts (windows, workers) to send each other messages.

The BroadcastChannel interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel.

It differ from the postMessage api by the fact that the child windows are not meant to be declared in the parent page. This way there is no more parents nor childrens.

Example sending:

new BroadcastChannel('myapp').postMessage('Hello?');

Example receiving:

new BroadcastChannel('myapp').addEventListener('message', function(e){
  console.log(e.data) 
})

This way, we can count tabs, or even inform the current active states to other tabs, etc.

Usage feedback since this post. The BroadcastChannel api is quite simple, but permit to rethink architectures.

This allows import modules to talk to each others, this simplify the composition of scripts.

I do not feel the need of webpacked composed scripts to build complex stuffs. We can share objects -encoded in json- via the channels, call a «service» when needed, separate logics, templates, factories, events, services, much more easily.

This is spot on for memory usage and performances. We can create many channels feeding in parallel some big flow of data, this has little effects on ram/cpu and interface responsiveness.

Less variables, less logic, the data broadcasted are directly garbaged. The coding style is pretty similar as websockets, event-driven, this is just local(s) socket(s).

Event-driven architecture (EDA) is a software architecture paradigm promoting the production, detection, consumption of, and reaction to events.


[MDN] Broadcast_Channel_API

https://caniuse.com/#feat=broadcastchannel

like image 162
NVRM Avatar answered Sep 25 '22 15:09

NVRM