HTML and CSS Reference
In-Depth Information
To test if the browser supports Web Sockets, use the following feature-detect for the
WebSocket API:
var websockets_support = !!window.WebSocket;
Now, let's build a simple application with chat room-type functionality, where a user
may read the current list of messages and add her own message to the room.
We'll have a text entry box where new messages are written before being sent, and we'll
have a list of messages in the chat room. We don't need features such as login or au-
thentication here, only simple chat room message sending and receiving:
<!DOCTYPE html>
<title>Our Chatroom</title>
<script src="chatroom.js"></script>
<h1>Our Chatroom</h1>
<div id="chatlog"></div>
<input id="newmsg" /><br />
<input type="button" value="Send Message" id="sendmsg" />
Now, let's examine the JavaScript in chatroom.js :
var chatcomm = new WebSocket ("ws://");
chatcomm. onmessage = function(msg) {
msg = JSON.parse(msg); // decode JSON into object
var chatlog = document.getElementById("chatlog");
var docfrag = document.createDocumentFragment();
var msgdiv;
for (var i=0; i<msg.messages.length; i++) {
msgdiv = document.createElement("div");
chatcomm. onclose = function() {
alert("The chatroom connection was lost. Refresh page to reconnect.");
document.getElementById("sendmsg").addEventListener("click", function(){
var newmsg = document.getElementById("newmsg");
chatcomm. send (newmsg.value); // send the message to the server
Search WWH ::

Custom Search