Search code examples
javascripthtmltabscommunicationpostmessage

Communication between browser tabs


I've an HTML page (file main.html) opening a new tab in the same domain using JavaScript with the window.open("newtab.html") method.

In the new tab users do something ending their activity clicking a button. At this point, I would like to send a message to the opener window. I tried with postMessage, but from a new tab I can't have a reference to the opener.

From the new tab I'd like something like, but I've "ko"

var w = window.opener;
if (w) {
    w.postMessage("hi", "http://10.150.10.43");
} else {
    alert("ko");
}

What is the best way to send message from the secondary tab/window to the main one (in the same domain)?


Solution

  • That is strange. Opening a new window with window.open("newtab.html") should give the newly opened window the ability to reference the opener via window.opener.

    Anyway, there are several other options for communicating between two windows on the same domain. I think that the following two are the easiest to implement:

    1. Use localStorage. If you store some data under some key into localStorage in the new tab window, then the opener window will get a storage event. If you catch the event with a handler, you can read the data from localStorage that you wrote from the new tab window. Note that events are fired only if both pages are on the same domain, and if there are actually two windows in question (events are not fired within the same window that wrote data). For more info on how to do this -- see for example: http://diveintohtml5.info/storage.html

    2. Use shared Web workers. A web worker is a JS script that is executed in the background on a separate thread. Shared web workers are a special type of Web workers that allow any number of parent documents to communicate with a single worker. So, you could use the worker to relay messages between the opener window and the new tab window. The API for communicating with a workers is very similar to the postMessage API. For more info on how to do this -- see for example: http://www.sitepoint.com/javascript-shared-web-workers-html5/.