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: "", // 发送者
receiver: "", // 接收者
setTitle: function (chatEl) {
var receiver = this.getReceiver(chatEl);
chatEl.find(".title").html("和" + receiver + "聊天对话中");
},
getReceiver: function (chatEl) {
var receiver = chatEl.attr("receiver");
if (~receiver.indexOf("@")) {
receiver = receiver.split("@")[0];
}
return receiver;
},
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 = [ "<span style=‘", styleTpl, "‘>", content, "</span>" ].join("");
}
return [
‘‘,
‘<p class="msg">‘, 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.innerHTML;
content = $.trim(content);
content = content.replace(new RegExp("<br>", "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 = [ "<span style=‘", styleTpl, "‘>", content, "</span>" ].join("");
remote.jsjac.chat.sendMessage(content, receiver);
}
// 清空发送区域
$(doc).find("body").html("");
}
},
faceImagePath: "images/emotions/",
faceElTpl: function (i) {
return [
"<img src=‘",
this.faceImagePath,
(i - 1),
"fixed.bmp‘ gif=‘",
this.faceImagePath,
(i - 1),
".gif‘/>"
].join("");
},
// 创建表情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("<br/>");
}
}
$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 = "<img src=‘" + $(this).attr("gif") + "‘/>";
var $chatMain = $(this).parents(".chat-main");
var win = $chatMain.find("iframe[name^=‘sendMessage‘]").get(0).contentWindow;
var doc = win.document;
sendMessageEditor.insertAtCursor(imgEL, doc, win);
});
// 表情隐藏
$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);
});
},
/***
* 发送消息工具栏按钮事件方法
**/
toolBarHandler: function () {
var $chat = $(this).parents(".chat-main");
var targetCls = $(this).attr("class");
if (targetCls == "face") {
$chat.find("#face").show(150);
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());
}
}
// 设置sendMessage iframe的style css
_opts.writeSendStyle();
},
// 设置sendMessage iframe的style css
writeSendStyle: function () {
var styleTpl = _opts.sendMessageStyle.getStyleTpl();
var styleEL = [‘<style type="text/css">body{‘, styleTpl,‘}</style>‘].join("");
$("body").find("iframe[name^=‘sendMessage‘]").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;
},
$(".no-msg").click(function () {
$(".chat-main:hidden").each(function (i, item) {
var top = i * 10 + 50;
var left = i * 20 + 50;
$(this).show(500).css({top: top, left: left});
});
});
con.registerIQGet(‘query‘, NS_VERSION, remoteChat.handleIqVersion);
con.registerIQGet(‘query‘, NS_TIME, remoteChat.handleIqTime);
},
// 发送远程消息
sendMessage: function (msg, to) {
try {
if (msg == "") {
return false;
}
var user = "";
if (to) {
if (!~to.indexOf("@")) {
user += "@" + remote.jsjac.domain;
to += "/" + remote.jsjac.resource;
} else if (~to.indexOf("/")) {
user = to.substr(0, to.indexOf("/"));
}
} else {
// 向chat接收信息区域写消息
if (remote.jsjac.chat.writeReceiveMessage) {
var html = "你没有指定发送者的名称";
alert(html);
//remote.jsjac.chat.writeReceiveMessage(receiverId, "server", html, false);
}
return false;
}
var userJID = "u" + hex_md5(user);
$("#" + userJID).find(remote.receiver).val(to);
// 构建jsjac的message对象
var message = new JSJaCMessage();
message.setTo(new JSJaCJID(to));
message.setType("chat"); // 单独聊天,默认为广播模式
message.setBody(msg);
// 发送消息
remote.connection.send(message);
return false;
} catch (e) {
var html = "<div class=‘msg error‘‘>Error: " + e.message + "</div>";
remote.console.info(html);
return false;
}
},
// 退出、断开链接
logout: function () {
var presence = new JSJaCPresence();
presence.setType("unavailable");
if (remote.connection) {
remote.connection.send(presence);
remote.connection.disconnect();
}
},
errorHandler: function (event) {
var e = event || window.event;
remote.console.errorEL().html(e);
if (remote.connection && remote.connection.connected()) {
remote.connection.disconnect();
}
return false;
},
unloadHandler: function () {
var con = remote.connection;
if (typeof con != "undefined" && con && con.connected()) {
// save backend type
if (con._hold) { // must be binding
(new JSJaCCookie("btype", "binding")).write();
}
if (con.suspend) {
con.suspend();
}
}
},
writeMessage: function (userJID, userName, content) {
// 向chat接收信息区域写消息
if (remote.jsjac.chat.writeReceiveMessage && !!content) {
remote.jsjac.chat.writeReceiveMessage(userJID, userName, content, false);
}
},
// 重新连接服务器
reconnection: function () {
remote.jsjac.register = false;
if (remote.connection.connected()) {
remote.connection.disconnect();
}
remote.jsjac.chat.login();
},
/* ########################### Handler Event ############################# */
handleIQ: function (aIQ) {
var html = "<div class=‘msg‘>IN (raw): " + aIQ.xml().htmlEnc() + "</div>";
remote.console.info(html);
remote.connection.send(aIQ.errorReply(ERR_FEATURE_NOT_IMPLEMENTED));
},
handleMessage: function (aJSJaCPacket) {
var user = aJSJaCPacket.getFromJID().toString();
//var userName = user.split("@")[0];
//var userJID = "u" + hex_md5(user);
var content = aJSJaCPacket.getBody();
var html = "";
html += "<div class=\"msg\"><b>消息来自 " + user + ":</b><br/>";
html += content.htmlEnc() + "</div>";
remote.console.info(html);
$.WebIM.messageHandler(user, content);
},
handlePresence: function (aJSJaCPacket) {
var user = aJSJaCPacket.getFromJID();
var userName = user.toString().split("@")[0];
var html = "<div class=\"msg\">";
if (!aJSJaCPacket.getType() && !aJSJaCPacket.getShow()) {
html += "<b>" + userName + " 上线了.</b>";
} else {
html += "<b>" + userName + " 设置 presence 为: ";
if (aJSJaCPacket.getType()) {
html += aJSJaCPacket.getType() + ".</b>";
} else {
html += aJSJaCPacket.getShow() + ".</b>";
}
if (aJSJaCPacket.getStatus()) {
html += " (" + aJSJaCPacket.getStatus().htmlEnc() + ")";
}
}
html += "</div>";
remote.console.info(html);
// 向chat接收信息区域写消息
remote.jsjac.chat.writeMessage("", userName, html);
},
handleError: function (event) {
var e = event || window.event;
var html = "An error occured:
"
+ ("Code: " + e.getAttribute("code")
+ "\nType: " + e.getAttribute("type")
+ "\nCondition: " + e.firstChild.nodeName).htmlEnc();
remote.error(html);
var content = "";
switch (e.getAttribute("code")) {
case "401":
content = "登陆验证失败!";
break;
// 当注册发现重复,表明该用户已经注册,那么直接进行登陆操作
case "409":
//content = "注册失败!\n\n请换一个用户名!";
remote.jsjac.chat.reconnection();
break;
case "503":
content = "无法连接到IM服务器,请检查相关配置!";
break;
case "500":
var contents = "服务器内部错误!\n\n连接断开!<br/><a href=‘javascript: self.parent.remote.jsjac.chat.reconnection();‘>重新连接</a>";
remote.jsjac.chat.writeMessage("", "系统", contents);
break;
default:
break;
}
if (content) {
alert("WeIM: " + content);
}
if (remote.connection.connected()) {
remote.connection.disconnect();
}
},
// 状态变化触发事件
handleStatusChanged: function (status) {
remote.console.info("<div>当前用户状态: " + status + "</div>");
remote.dbger.log("当前用户状态: " + status);
if (status == "disconnecting") {
var html = "<b style=‘color:red;‘>你离线了!</b>";
// 向chat接收信息区域写消息
remote.jsjac.chat.writeMessage("", "系统", html);
}
},
// 建立链接触发事件方法
handleConnected: function () {
remote.console.clear("debug"); // reset
remote.connection.send(new JSJaCPresence());
},
// 断开链接触发事件方法
handleDisconnected: function () {
},
handleIqVersion: function (iq) {
remote.connection.send(iq.reply([
iq.buildNode("name", remote.jsjac.resource),
iq.buildNode("version", JSJaC.Version),
iq.buildNode("os", navigator.userAgent)
]));
return true;
},
handleIqTime: function (iq) {
var now = new Date();
remote.connection.send(iq.reply([
iq.buildNode("display", now.toLocaleString()),
iq.buildNode("utc", now.jabberDate()),
iq.buildNode("tz", now.toLocaleString().substring(now.toLocaleString().lastIndexOf(" ") + 1))
]));
return true;
}
};
这个文件的代码就是用jsjac库和openfire建立通信的核心代码,代码中已经有注释,这里我就不再赘述。如果有什么不懂的可以给我留言。
init: function (userJID) {
//打开document对象,向其写入初始化内容,以兼容FireFox
var doc = sendMessageEditor.getDoc();
doc.open();
var html = [
‘<html>‘,
‘<head><style type="text/css">body{border:0;margin:0;padding:3px;height:98%;cursor:text;background-color:white;font-size:12px;font-family:Courier,serif,monospace;}</style></head>‘,
‘<body jid="‘, userJID, ‘"></body>‘,
‘</html>‘].join("");
doc.write(html);
//打开document对象编辑模式
doc.designMode = "on";
doc.close();
},
getContent: function () {
var doc = sendMessageEditor.getDoc();
//获取编辑器的body对象
var body = doc.body || doc.documentElement;
//获取编辑器的内容
var content = body.innerHTML;
//对内容进行处理,例如替换其中的某些特殊字符等等
//Some code
//返回内容
return content;
},
//统一的执行命令方法
execCmd: function (cmd, value, d){
var doc = d || sendMessageEditor.getDoc();
//doc对象的获取参照上面的代码
//调用execCommand方法执行命令
doc.execCommand(cmd, false, value === undefined ? null : value);
},
getStyleState: function (cmd) {
var doc = sendMessageEditor.getDoc();
//doc对象的获取参考上面的对面
//光标处是否是粗体
var state = doc.queryCommandState(cmd);
if(state){
//改变按钮的样式
}
return state;
},
insertAtCursor: function (text, d, w){
var doc = d || sendMessageEditor.getDoc();
var win = w || sendMessageEditor.getWin();
//win对象的获取参考上面的代码
if (/msie/.test(agent)) {
win.focus();
var r = doc.selection.createRange();
if (r) {
r.collapse(true);
r.pasteHTML(text);
}
} else if (/gecko/.test(agent) || /opera/.test(agent)) {
win.focus();
sendMessageEditor.execCmd(‘InsertHTML‘, text, doc);
} else if (/safari/.test(agent)) {
sendMessageEditor.execCmd(‘InsertText‘, text, doc);
}
}
};
5、css样式 chat-2.0.css
/**
* function: im web chat css
* author: hoojo
* createDate: 2012-5-26 上午11:42:10
*/
@CHARSET "UTF-8";