The AppKey of an app.
Authentication method for logging in to IM (default value: 0):
Note that if you use dynamic tokens for authentication, you need to listen to the onwillreconnect callback and set the dynamic token in onwillreconnect
Whether to automatically mark the message as read, the default value is true.
If false, all messages (including plain messages and system notifications) will not be automatically marked as read, and you must manually call the interface markMsgRead to mark messages read to notify the server that the message has been received. Otherwise, the server will send messages as offline messages and offline system notifications during initialization.
Custom client type, set an integer greater than 0. You can configure custom multi-device login strategy, and the specific strategy can be configured in the CommsEase console. For more information, see: Custom multi-device login
Client custom tag. Up to 32 characters.
For multi-device login, if login on a device with this field, other devices can obtain the field information using the onloginportchange callback.
//Device 1
NIM.getInstance({
account: 'test1',
onloginportschange: function(err, data) {
//When device 2 logs in, print:
//data: [{
// account: 'test1',
// customTag: 'customTag from test1',
// connectionId, deviceId, ip, mac, online, os, time, type
//}]
console.log('data', data)
}
})
//Device 2
NIM.getInstance({
account: 'test1',
customTag: 'customTag from test1'
})
Whether to use IM business database (indexedDb), default value: true
Whether to store the log in the local database, the default value is true, the log is stored in the local database by default. To retrieve the logs in the local database, contact our technical support for help.
Specify whether to print the debugging log.. The default value is false.
The default backup address for persistent connection address
The validity period of logs in the local database. Unit: hour, the default value is 72 hours.
Whether the CDN link of the file in the message content is forced to use the HTTPS protocol. The default value is false
Whether to enable the standby LBS address. The default value is true. NIM SDK will store the last successfully connected LBS address in the browser's local cache localStorage as a standby option. When the primary LBS address is unavailable, the SDK will try to request the standby LBS address.
Array of custom standby LBS addresses, use custom interfaces to proxy LBS to prevent carriers from hijacking. When the primary LBS address is unavailable and none of the standby LBS addresses cached locally by the browser is available, NIM SDK will try to request a custom standby LBS address with a lower priority than the one cached in local storage mentioned by lbsBackup.
LBS addresses are used by default
Log level, the default is off and no log is output. This property affects both indexdb and the log level in the console
Login custom extension field, which can be forwarded to the specified third-party server, and will not be synchronized to other devices. authType is 2. If IM login authentication is performed using a third-party callback, required for third-party webhook.
Whether to enable automatic reconnection, the default value is true. If the persistent connection is closed due to network problems or heartbeat timeout, NIM SDK will automatically try to reconnect to the server by default.
Storage scenarios of uploaded files on NOS.
The validity period of uploaded files stored on NetEase Object Storage (NOS).
On-premises deployment configuration
Whether to enable A/B testing, main version: true, stable version: false by default
Note: Supported by stable version v8.9.111~8.9.1xx, and supported by main version > 9.11.0
Whether to enable data reporting, the default value is true
Note: Supported by stable version v8.9.111~8.9.1xx, and supported by main version > 9.11.0
Whether to enable converged storage, main version: true, stable version: false by default
Note: Supported by stable version v8.9.111~8.9.1xx, and supported by main version > 9.11.0
Whether to enable quick automatic reconnection, the default value is false. If the value is set to true, NIM SDK will monitor the browser's offline and online events to detect network disconnection and recovery, and will implement corresponding disconnection and reconnection strategies.
The maximum number of retries for reconnection. If the number of retries exceeds the number, the SDK will not try to reconnect again.
Whether to continue to reset the unread count of the current client after failing to reset the unread count of the conversation. The default value is true
Whether to update the unread count and the last message in a conversation and trigger the onupdatesessions callback after clearing the message history by calling clearServerHistoryMsgsWithSync. The default value is true.
Whether to update the unread count of the conversation after unsending a message, the default value is true
Assuming this parameter is set to true and a conversation has 2 unread messages. If one of the messages is unsent, the unread count becomes 1.
Get whether HTTPS is used to connect to the server. The default value is true.
The number of concurrent socket connections.
Supported since v9.12.0 The maximum number of Socket concurrent connections. Valid values: an integer between 1 and 3. The default value is 1, no concurrent connections are supported. If you need more Socket connections, you can set this parameter.
Whether to synchronize signaling unread messages, default value: true
Note: supported by SDK v9.10.0 and later
Whether to synchronize offline broadcast messages during initialization, default value false.
Whether to synchronize the user's information in each group during initialization. The default value is true. If false, the onMyTeamMembers
callback will not be triggered during initialization.
onMyTeamMembers
returns the profile of the current user in each group, including but not limited to:
Whether to synchronize user profiles during initialization, default value: true
Whether to synchronize read receipt timestamps during initialization, default value: true.
If true, you can view the timestamp of the read receipt in a conversation based on session.msgReceiptTime by onsessions
during initialization.
Whether to synchronize the blacklist and list of muted members. The default value is true. If the value is set to true, synchronize the blacklist and the list of muted members during initialization.
Whether to synchronize private messages and message history for sync inf advanced groups, the default value is true.
The default value is false. This parameter has two purposes:
Whether to synchronize the pinned conversations during initialization, the default value is false. The data of pinned conversations are delivered to users using onStickTopSessions and attached to the isTop attribute of the conversation.
Whether to synchronize the messages for sync in supergroups during initialization, the default value is true.
Whether to synchronize the supergroup list during initialization, the default value is true
IM account login credentials This login credential will only be verified once when logging in to IM (establishing a persistent connection between the SDK and CommsEase server).
Whether to process logs such as log storage, log reporting, etc.
This function will get parameters for SDK log for use.
const logs = []
setInterval(() => {
if (logs.length > 0) {
//Every 2 minutes, upload the logs to your app server
//...
//Clear logs
logs = []
}
}, 120000)
NIM.getInstance({
logFunc: {
log: function (data) {
logs.push(`log: ${data}`)
},
warn: function (data) {
logs.push(`warn: ${data}`)
},
info: function (data) {
logs.push(`info: ${data}`)
},
debug: function (data) {
logs.push(`debug: ${data}`)
},
error: function (data) {
logs.push(`error: ${data}`)
}
}
})
When a member joins the supergroup, all online clients including the client of the member will trigger this callback.
Account to be added
Member profile
Group information
When a member joins the group, all online clients including the client of the member will trigger this callback function.
Account to be added
Member profile
Group information
Callback invoked when MessageLogInterface.clearServerHistoryMsgsWithSync is invoked during multi-device synchronization or synchroning data during initialization.
No matter whether the callback is registered, the SDK will clear the corresponding data of the conversation in the local database when the message history on the server is deleted.
When the event takes place, the user should clear the messages in the conversation earlier than the event time
Callback invoked when a group is created.
Callback invoked when a local message is deleted when the account is logged in on multiple devices.
Extension field
Note that the data must be in JSON string
Time when a message is deleted
account of a sender
The message ID generated by the client test can be used as the unique primary key of the message.
The ID used by the server to distinguish messages, used to get message history and keywords for searching message history.
Messaging use case:
Timestamp
ID of a recipient, account ID or group ID
When deleting a quick comment, the message sender and the logged-in devices of the commenter will get notified by the onDeleteQuickComment callback
// key: sessionId
// value.msgs: List of messages
// value.msgs[idx].quickComments: List of comments
const sessions = {}
function getSessionId(msg) {
if (msg.scene !== 'p2p') {
return `${msg.scene}-${msg.to}`
} else if (msg.from === nim.account) {
return `p2p-${msg.to}`
} else {
return `p2p-${msg.from}`
}
}
nim = NIM.getInstance({
// Receive a notification to delete a comment, and remove the comment from the quick comment queue
onDeleteQuickComment: function(msg, comment) {
const sessionId = getSessionId(msg)
const session = sessions[sessionId]
if (session) {
for (let _msg of session.msgs) {
if (_msg.idClient === msg.idClient) {
// Find the commented message
_msg.quickComments = _msg.quickComments || []
// Delete quick comments of the same type from the same account
for (let i = _msg.quickComments.length - 1; i >= 0; i--) {
if (_msg.quickComments[i].from === comment.from && _msg.quickComments[i].body === comment.body) {
_msg.quickComments.splice(i, 1)
break
}
}
}
}
}
}
})
account of a sender
The message ID generated by the client test can be used as the unique primary key of the message.
The ID used by the server to distinguish messages, used to get message history and keywords for searching message history.
Messaging use case:
Timestamp
ID of a recipient, account ID or group ID
Quick comment
Extension
ID of the account making the comment.
time when the comment is posted.
When the group is deleted, all members in the supergroup get notified by onDismissTeam. You can delete a supergroup by calling the server API.
const superTeamById = {}
nim = NIM.getInstance({
onDismissSuperTeam: function (data) {
console.log('debug++ onDismissSuperTeam', data)
const teamId = data.teamId
delete superTeamById[teamId]
}
})
When the group is deleted, all members in the group get notified by onDismissTeam
Callback invoked when a read receipt for a message is received. Note that needMsgReceipt = true when sending group messages, otherwise the onMsgReceipts callback cannot be triggered.
(Synchronization during initialization, online, multi-device synchronization) received the current account, profile settings in each group. For example, whether the current user is the group owner, administrator, whether Do Not Disturb is turned on.
Note: The member profile in a supergroup contain a field for muting the supergroup. You can combine the field into session.
(Synchronization during initialization, online, multi-device synchronization) received the current account, profile settings in each group. For example, whether the current user is the group owner, administrator, whether Do Not Disturb is turned on.
When adding, updating, or deleting the PIN tag of a message, the onPinMsgChange callback will be triggered.
// key: sessionId
// value.msgs: List of messages in a conversation
// value.msgs[idx].pinInfo: If there is pinInfo, the message is collected
const sessions = {}
// Find the PIN messages in the conversation list
function getMsgInSessions(msg) {
const sessionId = getSessionId(msg)
const session = sessions[sessionId]
if (session) {
const msgs = session.msgs || []
for (let _msg of msgs) {
if (msg.idClient === _msg.idClient) {
return _msg
}
}
}
}
function getSessionId(msg) {
if (msg.scene !== 'p2p') {
return `${msg.scene}-${msg.to}`
} else if (msg.from === nim.account) {
return `p2p-${msg.to}`
} else {
return `p2p-${msg.from}`
}
}
nim = NIM.getInstance({
onPinMsgChange: function (data, action) {
const _msg = getMsgInSessions(data.msg)
if (action === 'add' || action === 'update') {
_msg.pinInfo = data.pinTag
} else {
_msg.pinInfo = undefined
}
}
})
The structure of pinned messages
the extension field of PIN messages
The user adding the PIN tag to the message
After adding a quick comment to a message, the sender and the logged-in devices will get notified by the onQuickComment callback.
Quick comments can only use fields of integer type. Quick comments are often used to add emoj replies to messages. For example, 1 for flowers, and 2 for happiness.
When the same user sends multiple quick comments of the same type, the previous comment will be overwritten by the subsequent ones.
// key: sessionId
// value.msgs: List of messages
// value.msgs[idx].quickComments: List of comments
const sessions = {}
function getSessionId(msg) {
if (msg.scene !== 'p2p') {
return `${msg.scene}-${msg.to}`
} else if (msg.from === nim.account) {
return `p2p-${msg.to}`
} else {
return `p2p-${msg.from}`
}
}
nim = NIM.getInstance({
//Receive a new comment, and append the comment to the quick comment queue of the message.
onQuickComment: function(msg, comment) {
const sessionId = getSessionId(msg)
const session = sessions[sessionId]
if (session) {
for (let _msg of session.msgs) {
if (_msg.idClient === msg.idClient) {
// Find the commented message
_msg.quickComments = _msg.quickComments || []
// Remove the quick comments of the same type from the same account
for (let i = _msg.quickComments.length - 1; i >= 0; i--) {
if (_msg.quickComments[i].from === comment.from && _msg.quickComments[i].body === comment.body) {
_msg.quickComments.splice(i, 1)
break
}
}
_msg.quickComments.push(comment)
}
}
}
}
})
account of a sender
The message ID generated by the client test can be used as the unique primary key of the message.
The ID used by the server to distinguish messages, used to get message history and keywords for searching message history.
Messaging use case:
Timestamp
ID of a recipient, account ID or group ID
Quick comment
Custom extension
ID of the account making the comment.
time when the comment is posted.
When a member leaves the supergroup, all online clients including the client of the member will trigger this callback.
Added IM account(accid)
Group information.
Note: The team
field does not exist for scenarios when a member leaves a group and the onRemoveSuperTeamMembers callback is triggered.
Group ID
When a member leaves the group, all online clients including the client of the member will trigger this callback.
Added IM account(accid)
Group information.
Note: The team
field does not exist for scenarios when a member leaves a group and the onRemoveSuperTeamMembers callback is triggered.
Group ID
Receive pinned conversation information synchronized during initialization.
Callback invoked when the list of supergroups is synchronized.
const superTeamById = {}
nim = NIM.getInstance({
syncSuperTeams: true
onSuperTeams: function (teamArr) {
for (let team of teamArr) {
superTeamById[team.teamId] = team
}
}
})
The supergroup owner receives the notification when the supergroup is created (supergroups can only be created by calling the server API)
After calling updateServerSession, the logged-in devices get notified by this callback
data.teamMsgReceipts:
When the ownership of a supergroup changes, all online group members will get notified by this callback. The parameters include the group information, new and original group owner.
The original owner
The new group owner
When the ownership of a group changes, all online group members will get notified by this callback
The original owner
group member ID (group ID + account)
Get the type of a group member.
Get the update time
The new group owner
group member ID (group ID + account)
Get the type of a group member
Get the update time
Callback invoked when the group profile is updated, or when the mute status of the supergroup is updated, and the online members in the group will get notified by this callback
When administrators are assigned or unassigned in the supergroup, online group members will get notified by this callback
Account to be added
Whether the member is administrator
If false, the administrator is unassigned.
Basic info about the member to be assigned administrator.
Group basic info
Callback invoked when the group member information changes.
After the specified member is muted or unmuted, all online members in the supergroup will get notified by this callback
Account to be added
Basic info about the member to be assigned administrator.
Whether the group is muted.
If false, the member is unmuted.
Group basic info
Callback invoked when the group profile is updated, or when the mute status is updated, and the online members in the group will get notified by this callback
When administrators are assigned or unassigned in the group, online group members will get notified by this callback
Account to be added
Whether the member is administrator
If false, the administrator is unassigned.
Basic info about the member to be assigned administrator.
Group basic info
Group member update timestamp
Group ID
After the specified member is muted or unmuted, all online members in the group will get notified by this callback
Account to be added
Basic info about the member to be assigned administrator.
group member ID (group ID + account)
Whether the member is muted
Group ID
Get the type of a group member
Get the update time
Whether the group is muted.
If false, the member is unmuted.
Group basic info
Callback that returns the blocklist during initialization. Note that the blacklist is one-way data transfer. Users in the blocklist cannot send messages to the current user. The current user can send message to the users in the blocklist
Callback invoked when broadcast messages are received online. Users can receive one or more broadcast messages online.
Callback invoked when offline broadcast messages are received. Users can receive one or more offline broadcast messages during initialization.
The callback for establishing a persistent connection between the SDK and the CommsEase server. Your app can prompt the network status on the interface using onwillreconnect, onconnect, and ondisconnect.
The callback triggered when the connection is established takes an object containing login information, with the following fields:
Connection ID of the current login
Country
Client custom tag. Up to 32 characters.
Public IP address
Device ID of the last login
Port
Callback invoked when custom system notifications are received online. Users can receive custom system notifications online.
The SDK only transfer custom system notifications, and does not parse and store custom system notifications, or manage the unread count. You can manipulate custom system notifications as required. You can define notifications for custom events based on the business logic to implement various business scenarios. For example, the "typing indicator" from the peer in private chats.
For more information about custom system notifications, see: https://doc.yunxin.163.com/messaging/docs/zQxOTIwMDc?platform=web.
The callback for disconnecting the persistent connection between SDK and CommsEase server. Your app can prompt the network status on the interface using onwillreconnect, onconnect, ondisconnect.
code
, and jump to the login page// store refers to the object that stores data in your application
NIM.getInstance({
ondisconnect: function (res) {
// Set the prompt according to the code for disconnection
// for the code type of the first login, the status code returned by the server
// The character type is the status code when the login state is disconnected
if (typeof res.code === "number") {
if (res.code === 302) {
store.uistate.networkHint = "Account or password error";
} else if (res.code === 403) {
store.uistate.networkHint = "Login forbidden";
} else if (res.code === 422) {
store.uistate.networkHint = "account banned";
} else if (res.code === 417) {
store.uistate.networkHint = "Repeated login, the account is already logged in on another device";
} else {
store.uistate.networkHint = "The account cannot be logged in";
}
} else if (res.code === "kicked") {
if (res.reason === 'samePlatformKick' || res.reason === 'otherPlatformKick') {
store.uistate.networkHint = 'The account is already logged in on another device'
} else if (res.reason === 'serverKick') {
store.uistate.networkHint = 'The account was logged out'
} else {
store.uistate.networkHint = 'The account was logged out'
}
} else if (res.code === "allAttemptsFailed") {
store.uistate.networkHint = "Unable to connect to server";
} else if (res.code === "logout") {
store.uistate.networkHint = "The account was logged out";
} else {
store.uistate.networkHint = "The account was logged out";
}
redirect("loginPage");
}
})
Callback for errors during initialization.
Synchronize the friend list during initialization. If the account has no friends:
The callback invoked when the status of multi-device login changes. The callback can get the list of logged in devices. This callback is triggered when:
Callback for receiving messages for multi-device login or online. In addition to various types of basic messages, resent messages and forwarded messages will also trigger the onmsg callback.
In addition, some group messages displayed in the comversation also triggers the onmsg callback. When a group message triggers onmsg, the specific group message type can be viewed in the attach.type field. For more information, see Group notifications
Return the list of muted users during initialization Note that, like the blacklist, the list of muted users is one-way data transfer. The list of muted users is used for do-not-disturb:
The callback invoked when the profile is synchronized.
Callback invoked when custom system notifications are received online. Users can receive custom system notifications online.
The SDK only transfer custom system notifications, and does not parse and store custom system notifications, or manage the unread count. You can manipulate custom system notifications as required. You can define notifications for custom events based on the business logic to implement various business scenarios. For example, the "typing indicator" from the peer in private chats.
For more information about custom system notifications, see: https://doc.yunxin.163.com/messaging/docs/zQxOTIwMDc?platform=web.
Callback for receiving offline messages during initialization. For more information about the message sources, see the onmsg callback
Receive offline system notifications during initialization. Online system notifications are received using onsysmsg.
System notifications are divided into built-in system notifications and custom system notifications. For custom system notifications, see SystemMessageInterface.sendCustomSysMsg
The built-in system notifications includes two types: user relationship and groups. For information about types of system notifications, see Types of a system notifications
For information about events that trigger system notifications, see onsysmsg
Callback invoked when a notification is received for a subscribed event during initialization or online.
Before receiving a push notification for a subscribed event, you must subscribe to the event by calling subscribeEvent.
When subscribing to an event, you can set the validity period for the subscription. and within the period without, you do not need to subscribe to the event by calling subscribeEvent after re-login.
Callback invoked when retrieving messages for sync during initialization. For more information, see onmsg.
Synchronize system notifications for sync during initialization. Note that system notifications for sync only contain system notifications of type deleteMsg (triggered by recallMsg)
The list of conversations synchronized during initialization
Callback invoked when a group is created for multi-device login.
Callback invoked when the synchronization during initialization is complete If the database is enabled, the database operations must be performed after the synchronization is complete.
Callback for friend operations Friend operations include adding a friend, sending a friend request, accepting a friend request, rejecting a friend request, deleting a friend, and updating a friend's alias.
Account information for the following types:
Friend information. Valid friend operations:
Friend operations
Callback for synchronizaing the blocklist during initialization
Target account ID
Whether the account is included in the blocklist or the list of muted members.
true: Yes, false: No.
Details of the operation record
Target account ID
Update timestamp
The callback for synchronizing "the blocklist and list of muted users" across devices.
Target account ID
Whether the account is included in the blocklist or the list of muted members.
true: Yes, false: No.
Details of the operation record
Target account ID
Update timestamp
Callback invoked when a system notification is received online. System notifications for the offline phase are received using onofflinesysmsgs.
System notifications are divided into built-in system notifications and custom system notifications. For custom system notifications, see SystemMessageInterface.sendCustomSysMsg
The built-in system notifications includes two types: user relationship and groups. For information about types of system notifications, see Types of a system notifications
Get the unread count of system notifications during initialization. Note that this callback is only valid when db=true.
During initialization, the SDK will receive offline system notifications (onofflinesysmsgs) and system notifications for sync (onroamingsysmsgs), and then combine them with the system notifications saved in the database to calculate the unread count of system notifications.
Note that in the result, the following fields are included:
For functions that trigger system notifications, see onsysmsg
Callback for synchronizing the list of groups during initialization. - The attribute invalid
of teams
contains the groups the current user leaves.
When calling updateMyInfo, the multi-device login device will get notified by this callback
The callback invoked when the conversation is updated online. The update may include lastMsg, read receipt time, unread count, and whether to pin the conversation.
Callback invoked when a system notification is updated online. Triggered when a friend request is approved or rejected, a group application is accepted or rejected, and a group invitation is approved or rejected. When these events occur:
Callback invoked when the unread count of system notifications is updated online. Note that this callback is only valid when db=true.
The SDK updates the unread count if new system notifications are received. or, after the local system notifications are marked read, the SDK updates the unread count of the system notifications.
Note that in the result, the following fields are included:
For functions that trigger system notifications, see onsysmsg
Callback invoked when the group member information changes.
Callback invoked when the profile of a peer is updated.
Callback invoked when updating the friends profiles
The callback invoked when the SDK is reconnecting to the server. Your app can prompt the network status on the interface using onwillreconnect, onconnect, ondisconnect.
retry interval
number of retries
Determine whether notification messages are included in the unread message in the conversation. Notification messages include group notification messages and supergroup notification messages, see NIMGetInstanceOptions.onmsg.
Determine whether to ignore notification messages Notification messages include group notification messages and supergroup notification messages, see NIMGetInstanceOptions.onmsg.
IM account (also known as accid), which is the unique identifier of a user in CommsEase.
User accounts of your app and IM accounts (accid) are separate. CommsEase IM account is only used for authentication by CommsEase IM service. The IM account is not the user account of your app.