Four Ways HTML5 Moves Messages—and a New Home for My Experiments
As web applications become more time-sensitive and their responsibilities expand, message-based communication is appearing in more and more projects. HTML5 introduces several specifications intended to make these interactions easier and more practical. Four of the most important are WebSocket, Server-Sent Events, Cross-Document Messaging, and Channel Messaging.
WebSocket
WebSocket has been attracting increasing attention because persistent connections were traditionally a weak spot on the web. With a few straightforward JavaScript APIs, a page can establish a long-lived connection to a server. Besides enabling real-time communication, this avoids repeatedly transmitting HTTP headers, cookies, and other information attached to conventional requests.
There are two sides to WebSocket. The first is the browser-side JavaScript API used by front-end developers. The second is the WebSocket protocol itself, which defines how browsers implement that API and how servers participate in the connection. The protocol details matter primarily to browser and server developers, while most front-end work can remain focused on the JavaScript interface.
Its basic API looks like this:
socket = new WebSocket(url[, protocols]);
socket.url;
socket.readyState; // CONNECTING|OPEN|CLOSING|CLOSED
socket.send(...); // string|arraybuffer|blob
socket.onmessage = function (e) {
e.data;
};
socket.onopen = function (e) {...};
socket.onerror = function (e) {...};
socket.onclose = function (e) {...};
The WebSocket specification provides the full interface and protocol details.
Server-Sent Events
As its name suggests, Server-Sent Events lets a server push information to a browser more conveniently. It is lighter than WebSocket and has two clear advantages. First, it does not require a special protocol or an unusual server-side language; mainstream web technologies can handle it. Second, it concentrates on server-to-browser delivery rather than two-way communication, making many implementations simpler and more efficient.
A social feed is an obvious use case: new posts, comments, or private messages can appear in real time without the page repeatedly polling for updates.
Server-Sent Events, usually shortened to SSE, also has a simple browser API:
var source = new EventSource('./sse.php');
source.addEventListener('message', function (e) {e.data;...}, false);
source.addEventListener('add', function (e) {e.data;...}, false);
source.addEventListener('customEventType', function (e) {e.data;...}, false);
The server responds using a specific text format:
echo "event:customEventType"; // 确定事件类型
echo "data:content string here..."; // 返回数据内容
echo "retry:5000" // 5秒之后请求第二次;
The event field identifies the event type, data carries the message content, and retry tells the browser when to reconnect.
Cross-Document Messaging
Cross-Document Messaging is designed for communication between separate windows or workers. That includes embedded iframes, Web Workers, and windows opened with window.open. Allowing these different contexts to exchange messages makes it possible to combine web components in more flexible ways.
The basic pattern is concise:
// on top
iframe.postMessage('hello');
// on iframe
window.onmessage = function (e) {e.data;...}
This mechanism can also support communication across origins, provided that the receiving page explicitly permits the intended origin. That authorization boundary is important: cross-origin messaging should not be treated as unrestricted access.
Channel Messaging
Channel Messaging introduces another useful model. JavaScript creates a channel containing two port objects. References to those ports can then be passed elsewhere. No matter how far apart the two endpoints end up, a message posted through one port immediately produces a message event on the other, and communication works in both directions.
A minimal example looks like this:
var channel = new MessageChannel();
var port1 = channel.port1;
var port2 = channel.port2;
port1.onmessage = function (e) {e.data;...};
port2.postMessage('Hello Port1!');
Because the ports themselves can be transferred between execution contexts, Channel Messaging opens the door to some imaginative application architectures and experiments.
Beyond These Four APIs
Anyone exploring HTML5 messaging should also look at Web Workers and the related synchronous data APIs. Traditional browser APIs are often asynchronous and continue through callback functions, which can make code harder to follow. Inside a worker, long-running operations do not freeze the visible interface, so synchronous operations can sometimes be used without creating the same user-interface problem.
WebRTC is another important direction. It gives clients a much more active role in establishing and managing communication, extending the possibilities beyond the server-centered approaches described above.
A Combined Demo
I put together a small demonstration covering three of these technologies: Cross-Document Messaging, Channel Messaging, and Server-Sent Events. WebSocket is the only one not included. At the time of testing, WebKit-based browsers provided comparatively complete support for the features used in the demo.
The PHP required for the SSE endpoint is quite short. It simply returns the properly formatted event stream, so the demonstration focuses mainly on how the browser-side communication pieces fit together.
A New Site for Demos and Notes
Alongside the messaging demo, I have opened another website hosted on SAE and connected it to a recently purchased domain. It is still at an early stage, so there is not much material yet. For now, I have added some earlier demonstrations and presentation slides, together with a few notes about what I plan to build there. The site also has a new visual design whose reception remains to be seen.
The existing blog will continue to receive updates, although I may gradually guide more of the content and traffic toward the new site.