I recently implemented a JavaScript only communication system for sending messages between windows/tabs (just referred to as window for the remainder of this document) for Ariba.com. We have a very heavy-handed approach that requires identifying each window and queueing messages in the order that are sent, no matter the originating window. And the final kicker is that it needs to work on some older browsers.

We settled on a shared communication channel using the browser local storage, or cookies when local storage is unavailable. Since each window has its own UI thread processing the JavaScript, we also had to consider race conditions with reading and writing to the shared data store. Unfortunately, our solution required server-side logic for tab detection, so it is not applicable outside of Ariba. However, there was a lot of good learning to share, so I simplified the communication channel and rewrote the code to not need to keep track of the originating window.

This article introduces a system that can be used to send messages between windows using only JavaScript. This technique has some drawbacks to consider before using: it only allows one message to be on the stack at a time, it does not preserve message order (although, they tend to stay in order), and it does not guarantee message delivery (closing a window before all messages have been sent). But it should be fine for loss-tolerant operations, such as sending a message alerting the user that another window about to logout.

How it works…

We’ll break the discussion up into three sections: init, post message, and read message.

init

The init function is called automatically after the window_messenger script is loaded. It first starts a poll timer (default is five seconds) to periodically call the read_message function. Then the code sets up a reader and writer functions to handle reading and writing message internally. The code prefers to use window.localStorage, but will use a cookie when local storage is unavailable.

Lastly, it checks to see if there is already a message and updates variables to assume the message originated from this window. Since the messages contain no information indicating what window originated them, there is no way to know if the message originated from this window or another. And if it did originate from this window on a previous page, nobody would ever know to remove the message, since previous page JavaScript variables are lost. So, we assume it originated from this window, and if it did not, everything is still fine, because the real originating window will remove the message before the timer on this window does, and the current window will detect that and move on.

We make one assumption about this window not needing to process the message since it just reloaded.

post message

The postMessage function should be passed the string message to send to the other windows. It first checks if the message is currently being sent or sent by another window to prevent spamming messages. Next, when there is already a message being sent, we queue the message using a simple timeout, so it will try to send again after the next read cycle.

Otherwise, we write our message and follow it by a short timeout (this should be much shorter than a read cycle and is hardcoded to 500ms). The callback in the timeout double checks that the message is still the value in the data store, ensuring that another window did accidentally overwrite the current message. If a race occurred, we let the other message remain for the next cycle and queue up the message that we tried to write.

read message

The readMessage function is called periodically, and handles reading and removing messages. It first grabs the current message, then makes sure the message is not empty. When the current message is empty we set the sLastReceivedMessage variable to an empty string, so the system can accept the same message again if another window sends it. When the current message is not equal to sLastReceivedMessage, we send the message to all subscribing callback functions and update sLastReceivedMessage to the current message value.

When the current message equals sLastSentMessage, we activate logic to handle detecting when to remove the message. A cycle counter is incremented to indicate the number of times this code block executed for the current message. When the counter is greater than the number of cycles to persist (default is two cycles), the message is cleared from the data store.

To remove the message, an empty string is written to the shared data store. As with postMessage a short timeout is used to assert there was not a race to update the data store. When a race occurs, we do not need to do anything, because the next read message cycle will attempt to remove the message again. When there is no race, we go ahead and reset the counter and sLastSentMessage.

If another window writes the exact same message as the current window is trying to remove during the 500ms timeout, then the race logic will be triggered. This is most likely okay, because the duplicate message was just sent and processed by the other windows, so it is probably a spammy message.

There’s more…

As you can see, sending messages between windows can be done relatively simply, if it doesn’t need to be bullet-proof. I think this could be improved by using an SQL database or similar system in the browser, where messages can be written and removed in order, without worrying about race conditions. Alternatively, a set of 10 to 20 keys could be written to, writing to the next available slot and read out in order. This would allow multiple messages to be written and processed using the same technologies already implemented, but would require more complicated message tracking and handling of race conditions.