29 Communicating between browser windows

Posted: Dec 7, 2005, under DHTML. Updated: Nov 1, 2006. Add a comment!

This is probably obvious once you sit down and think about it, but I’m going to describe it anyway. You can communicate between any number of browser windows, in real time, using cookies set from JavaScript.

JavaScript is allowed to set and read cookies in the browser. Once a cookie is modified or created, it enters a common pool which is instantly accessible from any browser window.

Note: …Not really “any” browser window. Read my follow-up on cookie separation in modern browsers to see what exceptions apply.

Of course, there’s a security limitation in place: you can only access cookies which were set for the same domain as the currently loaded page. If you set the cookies from a page on the harddisk (domain file:///) you can only read them from a page which is also opened from the local harddisk. If you set them from a page loaded from http://www.mydomain.dom/ you can only read them from pages also opened from http://www.mydomain.dom/.

Here are two very simple HTML documents which will attempt to demonstrate this feature. First we have sender.html:

<h1>Sender</h1>

<p>Type into the text box below and watch the text appear automatically in the receiver.</p>

<form name="sender">
<input type="text" name="message" size="30" value="">
<input type="reset" value="Clean">
</form>

<script type="text/javascript"><!--
function setCookie(value) {
	document.cookie = "cookie-msg-test=" + value + "; path=/";
	return true;
}
function updateMessage() {
	var t = document.forms['sender'].elements['message'];
	setCookie(t.value);
	setTimeout('updateMessage()', 100);
}
updateMessage();
//--></script>

And then there’s receiver.html:

<h1>Receiver</h1>

<p>Watch the text appear in the text box below as you type it in the sender.</p>

<form name="receiver">
<input type="text" name="message" size="30" value="" readonly disabled>
</form>

<script type="text/javascript"><!--
function getCookie() {
	var cname = "cookie-msg-test=";
	var ca = document.cookie.split(';');
	for (var i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(cname) == 0) {
			return c.substring(cname.length, c.length);
		}
	}
	return null;
}
function updateMessage() {
	var text = getCookie();
	document.forms['receiver'].elements['message'].value = text;
	setTimeout('updateMessage()', 100);
}
updateMessage();
//--></script>

Open the two files in the browser in two separate windows. Place the windows side by side, and type something in the sender. You’ll see the message duplicated instantly in the receiver.

That’s pretty much all there is to it. While the security limitation can seem a bit restrictive, there are still plenty of legitimate uses. Especially when combined with remote procedure call scripting (such as XMLHttpRequest aka AJAX).