Mercurial > cosocket
diff openwebchat.js @ 45:27785e0ac4d8
Added error detection on the client-side.
author | Atul Varma <varmaa@toolness.com> |
---|---|
date | Tue, 28 Apr 2009 10:03:51 -0700 |
parents | d6467f3845ad |
children | 42b8c0229cd0 |
line wrap: on
line diff
--- a/openwebchat.js Tue Apr 28 08:32:25 2009 -0700 +++ b/openwebchat.js Tue Apr 28 10:03:51 2009 -0700 @@ -1,13 +1,29 @@ var OpenWebChat = { - startMessageListener: function startMessageListener(onMessage) { + startMessageListener: function startMessageListener(options) { var req = new XMLHttpRequest(); req.multipart = true; req.open('GET', 'listen/multipart', true); req.overrideMimeType('application/json'); req.addEventListener( + "error", + function() { + options.onError(null); + }, + false + ); + req.addEventListener( "load", function onload(evt) { - onMessage(JSON.parse(req.responseText)); + var msg; + var errorOccurred = false; + try { + msg = JSON.parse(req.responseText); + } catch (e) { + options.onError(e); + errorOccurred = true; + } + if (!errorOccurred) + options.onMessage(msg); }, false ); @@ -46,30 +62,39 @@ }); OpenWebChat.startMessageListener( - function(msg) { - var block = $('#templates .message').clone(); + {onMessage: function onMessage(msg) { + var block = $('#templates .message').clone(); - // Try to dynamically determine if the message is HTML or not. - var parser = new DOMParser(); - var dom = parser.parseFromString('<xml>' + msg.content + '</xml>', - 'text/xml'); - if (dom.firstChild.nodeName == 'parsererror') - $('.content', block).text(msg.content); - else - $('.content', block).html(msg.content); + // Try to dynamically determine if the message is HTML or not. + var parser = new DOMParser(); + var dom = parser.parseFromString('<xml>' + msg.content + '</xml>', + 'text/xml'); + if (dom.firstChild.nodeName == 'parsererror') + $('.content', block).text(msg.content); + else + $('.content', block).html(msg.content); - var author = msg.author ? msg.author : 'Anonymous'; - if (author != $('#content .author:last').text()) - $('.author', block).text(author); - else - $('.author', block).remove(); + var author = msg.author ? msg.author : 'Anonymous'; + if (author != $('#content .author:last').text()) + $('.author', block).text(author); + else + $('.author', block).remove(); + + $('.timestamp', block).text(msg.time); - $('.timestamp', block).text(msg.time); - - block.hide(); - $('#incoming-messages').append(block); - block.slideDown(function() { - window.scrollTo(0, $(window).height()); - }); + block.hide(); + $('#incoming-messages').append(block); + block.slideDown(function() { + window.scrollTo(0, $(window).height()); + }); + }, + onError: function onError(exception) { + if (window.console) + window.console.log('The error', exception, 'occurred.'); + var error = $('#templates .error').clone(); + error.hide(); + $('#incoming-messages').append(error); + error.slideDown(); + } }); });