Question

Cette question a déjà une réponse ici:

J'ai deux fenêtres: la fenêtre A et la fenêtre B.

  • La fenêtre A et la fenêtre B ont le même domaine
  • La fenêtre A et la fenêtre B n'ont pas de fenêtre parent.

Des questions:

  1. Est-il possible pour la fenêtre A pour obtenir une référence de la fenêtre B?
  2. Quelle est la façon la plus élégante de faire de la fenêtre un avis quelque chose à la fenêtre B?
    (y compris les nouvelles spécifications HTML5)

Deux façons dont je suis conscient de faire ceci:

  • Messagerie par serveur: où la fenêtre B Regulary demande au serveur si la fenêtre A a informé quelque chose
  • Messagerie par des données locales (HTML5): Lorsque la fenêtre A souhaite informer quelque chose, elle modifie les données locales, la fenêtre B Regulary vérifie les données locales pour toute modification.

Mais les deux manières ne sont pas si élégantes.
Par exemple, il serait bien d'obtenir une référence de la fenêtre B et d'utiliser Window.PostMessage () (HTML5)

L'objectif ultime est de faire quelque chose comme Facebook où si vous ouvrez 4 onglets Facebook et discuter dans un seul onglet, le chat est à jour dans chaque onglet Facebook, ce qui est soigné!

Était-ce utile?

La solution

Je m'en tiens à la solution de données locales partagée mentionnée dans la question en utilisant localStorage. Il semble que ce soit la meilleure solution en termes de fiabilité, de performance et de compatibilité du navigateur.

localStorage est implémenté dans tous les navigateurs modernes.

La storage L'événement tire quand autre Les onglets apportent des modifications à localStorage. Ceci est assez pratique à des fins de communication.

Des références peuvent être trouvées ici:
Espace archivage sur le Web
WebStorage - événement de stockage

Autres conseils

La norme BroadcastChannel permet de le faire. À l'heure actuelle, il est mis en œuvre dans Firefox et Chrome (puis-je utiliser, MDN):

// tab 1
var ch = new BroadcastChannel('test');
ch.postMessage('some data');

// tab 2
var ch = new BroadcastChannel('test');
ch.addEventListener('message', function (e) {
    console.log('Message:', e.data);
});

SharedWorker est la spécification whatwg / html5 pour un processus commun qui peut communiquer entre les onglets.

You said your:

utlimate goal is to make something like facebook where if you open 4 facebook tabs, and chat in one tab, the chat is actualize on every facebook tab, wich is neat!

That should happen as a by-product of your design, the views querying the model (probably the server) for updates to the chat, rather than your having to design in cross-view communication. Unless you're dealing with transferring huge amounts of data, why worry about it? It seems like it'll complicate things without a huge gain.

Years ago I found that if I did window.open using the name of an existing window and a blank URL, I got a reference to the existing window (this behavior is even documented on MDC and a comment on the MSDN docs suggests it works in IE as well). But that was years ago, I don't know how universal the support for it is in today's world, and of course you won't have a window name to look for unless all of your windows include a named iframe for communication, named uniquely via server-side code, and then communicated to the other windows by means of server-side code... (Scary thought: That might actually be feasible. Store the "current" window names related to a logged-in account in a table, give the list to any new window created that logs into that account, cull old inactive entries. But if the list is slightly out of date, you'll open new windows when searching for others... And I bet support is iffy from browser to browser.)

Besides the upcoming SharedWorker, you can also use cross-document messaging, which is much more widely supported. In this scenario, there must a be a main window that is responsible for opening all other windows with window.open. The child windows can then use postMessage on their window.opener.

If using flash is an option for you, there is also the much older LocalConnection virtually supported on any client with flash installed (example code).

Other fallbacks methods:
postMessage plugin for jQuery with window.location.href fallback for older browsers
cookie-based solution for non-instant communication

AFAIK, it is impossible to communicate across windows if they do not have the same parent.

If they have both been opened from a parent window, you should be able to get hold of the parent's variable references.

In the parent, open the windows like this:

childA = window.open(...);
childB = window.open(...)

in ChildA, access childB like this:

childB = window.opener.childA

I have a neat way to do such trick, but with restrictions: you should allow popups for your domain and you will get one page always opened (as tab or as popup) which will implement communications between windows.

Here's an example: http://test.gwpanel.org/test/page_one.html (refresh page after enabling popups for domain)

The main feature of this trick - popup is being opened with url fragment '#' in the end, this force browser to don't change window location and store all the data. And window.postMessage do the rest.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top