Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JavaScript and jQuery to build a BS Web chat application

2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use JavaScript and jQuery to build a BS Web chat application". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use JavaScript and jQuery to build a BS Web chat application".

This program can communicate with all applications connected to the Openfire server and send messages. If you want to run this program, you also need a chat server Openfire.

And the third-party library (JabberHTTPBind) that needs to communicate with Openfire in Http mode.

JabberHTTPBind is the form of Http bind transmission of XMPP protocol communication provided by jabber, which can complete the establishment of persistent connection communication between WebBrowser and Openfire.

You can send emoticons, change font styles (your font style can also be seen on the other side's interface), and on the right is a message showing / shrinking details.

Details of shrinkage

Partial screenshot of chat interface

The user logs in, registers, and sendTo indicates who you send chat messages to after logging in, and set up a chat window

After logging in successfully, you can see your login status in the log console or your connection request status in the firebug console.

Login failed

Only connecting, there will be no more.

After the login is successful, you can send a message to the specified user and set up the new user to whom you want to send the message. Click the new Chat button to create a new session.

If you have a new message, there will be a new message prompt in the title bar of the browser.

If all the windows in your current chat interface are closed, there will be a flashing icon in the lower right corner.

Development environment

System:Windows

JavaEE Server:Tomcat 5.0.28+/Tomcat 6

WebBrowser:IE6+, Firefox3.5+ and Chrome are already compatible with browsers

JavaSDK:JDK 1.6 +

Openfire 3.7.1

IDE:eclipse 3.2 、 MyEclipse 6.5

Develop dependent libraries

Jdk1.4+

Serializer.jar

Xalan.jar

Jhb-1.0.jar

Log4j-1.2.16.jar

Jhb-1.0.jar this is JabberHTTPBind. I typed the compiled class into a jar package.

JavaScript lib

Jquery.easydrag.js window drag JavaScript lib

Jquery-1.7.1.min.js jquery lib

Jsjac.js communication core library

Local.chat-2.0.js Local session window send message JavaScript Library

Remote.jsjac.chat-2.0.js remote session message JavaScript Library

Send.message.editor-1.0.js window Editor JavaScript Library

I. preparatory work

Jsjac JavaScript lib download: https://github.com/sstrigler/JSJaC/

If you don't like using jsjac JavaScript lib to communicate with Openfire, there is a plugin for jQuery that you can use. Download the address.

JQuery-XMPP-plugin https://github.com/maxpowel/jQuery-XMPP-plugin

There are all the third-party libraries that can support Openfire communication. If you are interested, you can study http://xmpp.org/xmpp-software/libraries/.

Jquery.easydrag download: http://fromvega.com/code/easydrag/jquery.easydrag.js

Jquery download: http://code.jquery.com/jquery-1.7.1.min.js

JabberHTTPBind jhb.jar download: http://download.csdn.net/detail/ibm_hoojo/4489188

Images picture material: http://download.csdn.net/detail/ibm_hoojo/4489439

Project catalogue structure

Second, core code demonstration

1. Main interface (login, message prompt, log, create new chat window) code index.jsp

WebIM Chat window.contextPath = ""; window ["serverDomin"] = "192.168.8.22" (function () {$("# login") .click (function () {var userName = $(": text [name = 'userName']"). Val (); var receiver = $("* [name='to']") .click () / / create a chat window application and set up the sender and message receiver $.webIM ({sender: userName, receiver: receiver}); / / Log in to the openfire server remote.jsjac.chat.login (document.userForm) $("label") .text (userName); $("form") .hide (); $("# newConn") .show ();}) Click ("# logout") .click (function () {/ / exit openfire login, unlink remote.jsjac.chat.logout (); $("form") .show (); $("# newConn") .hide () $("# chat"). Hide (800);}); $("# newSession") .click (function () {var receiver = $("# sendTo"). Val (); / / create a new chat window and set the message recipient (to whom? ) $.WebIM.newWebIM ({receiver: receiver}) UserName: password: register: sendTo: User: sendTo:

The following code is particularly important, which sets the address of your link openfire. You will not be able to communicate with an error in this address!

Window.contextPath = ""; window ["serverDomin"] = "192.168.8.22"

The $.WebIM method is the main function that overrides the basic configuration in local.chat and completes the creation of the chat window. The $.WebIM.newWebIM method creates a new window, except that the recipient of the message is a new user.

$.WebIM ({sender: userName, receiver: receiver}); $.WebIM.newWebIM ({receiver: receiver})

Remote.jsjac.chat.login (document.userForm); method is that the user logs in to the Openfire server

The parameters are as follows:

Httpbase: window.contextPath + "/ JHB/", / / request backend http-bind server url domain: window ["serverDomin"], / / "192.168.5.231", / / currently valid domain name username: ", / / login user name pass:", / / password timerval: 2000, / / set request timeout resource: "WebIM" / / Link Resource ID register: true / / whether to register or not

Remote.jsjac.chat.logout (); is the link that exits and breaks the openfire

2. Local chat application core code local.chat-2.0.js

/ * jquery local chat * @ version v2.0 * @ createDate-2012-5-28 * @ author hoojo * @ email hoojo_@126.com * @ blog http://hoojo.cnblogs.com & http://blog.csdn.net/IBM_hoojo * @ requires jQuery v1.2.3 or later, send.message.editor-1.0.js * Copyright (c) 2012 M. hoo * * / (function ($) {if (/ 1\. (0 | 1 | 2)\. (0 | 1 | 2) / .test ($.fn.jquery) | / ^ 1.1/.test ($.fn.jquery) {alert ('WebIM requires jQuery v1.2.3 or later! You are using v' + $.fn.jquery); return;} var faceTimed, count = 0; var _ opts = defaultOptions = {version: 2.0, chat: "# chat", chatEl: function () {var $chat = _ opts.chat If ((typeof _ opts.chat) = = "string") {$chat = $(_ opts.chat);} else if ((typeof _ opts.chat) = = "object") {if (! $chat.get (0)) {$chat = $($chat) }} return $chat;}, sendMessageIFrame: function (receiverId) {return $("iframe [name = 'sendMessage" + receiverId + "']) .get (0) .contentWindow;}, receiveMessageDoc: function (receiverId) {receiverId = receiverId |"; var docs = [] Each ($("iframe [name ^ = 'receiveMessage" + receiverId + "']"), function () {docs.push ($(this.contentWindow.document));}); return docs; / / return $($("iframe [name ^ = 'receiveMessage" + receiverId + "']") .get (0) .contentWindow.document) }, sender: ", / / sender receiver:", / / recipient setTitle: function (chatEl) {var receiver = this.getReceiver (chatEl); chatEl.find (".title") .html ("and" + receiver + "chat conversation") }, getReceiver: function (chatEl) {var receiver = chatEl.attr ("receiver"); if (~ receiver.indexOf ("@")) {receiver = receiver.split ("@") [0];} return receiver }, / / receive message iframe style receiveStyle: ['','', 'body {border:0;margin:0;padding:3px;height:98%;cursor:text;background-color:white;font-size:12px;font-family:Courier,serif,monospace }', '.msg {margin-left: 1em;} p {margin:0;padding:0;} .me {color: blue;} .you {color:green }','] .join (""), writeReceiveStyle: function (receiverId) {this.receiveMessageDoc (receiverId) [0] .get (0) .write (this.receiveStyle);}, datetimeFormat: function (v) {if (~ v)

< 10) { return "0" + v; } return v; }, getDatetime: function () { // 设置当前发送日前 var date = new Date(); var datetime = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate(); datetime = " " + _opts.datetimeFormat(date.getHours()) + ":" + _opts.datetimeFormat(date.getMinutes()) + ":" + _opts.datetimeFormat(date.getSeconds()); return datetime; }, /*** * 发送消息的格式模板 * flag = true 表示当前user是自己,否则就是对方 **/ receiveMessageTpl: function (userName, styleTpl, content, flag) { var userCls = flag ? "me" : "you"; if (styleTpl && flag) { content = [ "", content, "" ].join(""); } return [ '', _opts.getDatetime(), ' ', userName, ': ', '', content, ' ' ].join(""); }, // 工具类按钮触发事件返回html模板 sendMessageStyle: { cssStyle: { bold: "font-weight: bold;", underline: "text-decoration: underline;", italic: "font-style: oblique;" }, setStyle: function (style, val) { if (val) { _opts.sendMessageStyle[style] = val; } else { var styleVal = _opts.sendMessageStyle[style]; if (styleVal === undefined || !styleVal) { _opts.sendMessageStyle[style] = true; } else { _opts.sendMessageStyle[style] = false; } } }, getStyleTpl: function () { var tpl = ""; $.each(_opts.sendMessageStyle, function (style, item) { //alert(style + "#" + item + "#" + (typeof item)); if (item === true) { tpl += _opts.sendMessageStyle.cssStyle[style]; } else if ((typeof item) === "string") { //alert(style + "-------------" + sendMessageStyle[style]); tpl += style + ":" + item + ";"; } }); return tpl; } }, // 向接收消息iframe区域写消息 writeReceiveMessage: function (receiverId, userName, content, flag) { if (content) { // 发送消息的样式 var styleTpl = _opts.sendMessageStyle.getStyleTpl(); var receiveMessageDoc = _opts.receiveMessageDoc(receiverId); $.each(receiveMessageDoc, function () { var $body = this.find("body"); // 向接收信息区域写入发送的数据 $body.append(_opts.receiveMessageTpl(userName, styleTpl, content, flag)); // 滚动条滚到底部 this.scrollTop(this.height()); }); } }, // 发送消息 sendHandler: function ($chatMain) { var doc = $chatMain.find("iframe[name^='sendMessage']").get(0).contentWindow.document; var content = doc.body[xss_clean]; content = $.trim(content); content = content.replace(new RegExp(" ", "gm"), ""); // 获取即将发送的内容 if (content) { var sender = $chatMain.attr("sender"); var receiverId = $chatMain.attr("id"); // 接收区域写消息 _opts.writeReceiveMessage(receiverId, sender, content, true); //############# XXX var receiver = $chatMain.find("#to").val(); //var receiver = $chatMain.attr("receiver"); // 判断是否是手机端会话,如果是就发送纯text,否则就发送html代码 var flag = _opts.isMobileClient(receiver); if (flag) { var text = $(doc.body).text(); text = $.trim(text); if (text) { // 远程发送消息 remote.jsjac.chat.sendMessage(text, receiver); } } else { // 非手机端通信 可以发送html代码 var styleTpl = _opts.sendMessageStyle.getStyleTpl(); content = [ "", content, "" ].join(""); remote.jsjac.chat.sendMessage(content, receiver); } // 清空发送区域 $(doc).find("body").html(""); } }, faceImagePath: "images/emotions/", faceElTpl: function (i) { return [ "

"] .join (");}, / / create emoji html elements createFaceElement: function ($chat) {var faces = []; for (var I = 1; I)

< 100; i++) { faces.push(this.faceElTpl(i)); if (i % 11 == 0) { faces.push(""); } } $chat.find("#face").html(faces.join("")); this.faceHandler($chat); }, // 插入表情 faceHandler: function ($chat) { $chat.find("#face img").click(function () { $chat.find("#face").hide(150); var imgEL = "

"; var $chatMain = $(this) .conversation (" .chat-main "); var win = $chatMain.find (" iframe [name ^ = 'sendMessage'] ") .get (0) .contentWindow; var doc = win.document; sendMessageEditor.insertAtCursor (imgEL, doc, win);}) / / hide $chat.find ("# face, # face img") .Mouseover (function () {window.clearTimeout (faceTimed);}) .Mouseout (function () {window.clearTimeout (faceTimed)) FaceTimed = window.setTimeout (function () {$chat.find ("# face") .hide (150,700);}) }, / * send messages toolbar button event method * / toolBarHandler: function () {var $chat = $(this) .event (".chat-main"); var targetCls = $(this) .attr ("class") If (targetCls = = "face") {$chat.find ("# face") .show; window.clearTimeout (faceTimed); faceTimed = window.setTimeout (function () {$chat.find ("# face") .hide (150);}, 1000) } else if (this.tagName = = "DIV") {_ opts.sendMessageStyle.setStyle (targetCls);} else if (this.tagName = = "SELECT") {_ opts.sendMessageStyle.setStyle ($(this) .attr ("name"), $(this) .val ()) If ($(this) .attr ("name") = = "color") {$(this) .css ("background-color", $(this). Val ());}} / / set style css _ opts.writeSendStyle () of sendMessage iframe }, / / set style css writeSendStyle of sendMessage iframe: function () {var styleTpl = _ opts.sendMessageStyle.getStyleTpl (); var styleEL = ['body {', styleTpl,'}'] .join (") Find ("body") .each (function () {var $head = $(this.contentWindow.document) .find ("head"); if ($head.find ("style"). Size () > 1) {$head.find ("style:gt (0)") .remove () } if (styleTpl) {$head.append (styleEL);}}) }, isMobileClient: function (receiver) {var moblieClients = ["iphone", "ipad", "ipod", "wp7", "android", "blackberry", "Spark", "warning", "symbian"]; var flag = false For (var i in moblieClients) {if (~ receiver.indexOf (moblieClients [I])) {return true;}} return false }, / / chat interface html element chatLayoutTemplate: function (userJID, sender, receiver, product, flag) {var display = ""; if (flag) {display = "style='display: none;'" } return [',','' ',' 'Commodity details','

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report