Options
All
  • Public
  • Public/Protected
  • All
Menu

Interface NIMGetInstanceOptions

Hierarchy

  • NIMGetInstanceOptions

Index

Properties

Methods

Properties

account: string

IM account (also known as accid), which is the unique identifier of a user in CommsEase.

notice

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.

appKey: string

The AppKey of an app.

note

Get the AppKey of your app in the CommsEase console. For more information, see Create an application.

authType?: number

Authentication method for logging in to IM (default value: 0):

  • 0: Authentication using static tokens. The static token remains unchanged and is permanently valid by default, unless you refresh token using the server API.
  • 1: Authentication using dynamic tokens. Dynamic tokens can be configured with a validity period and are time-sensitive. This authentication method can effectively increase the security and reduce the risk of password leakage. For information about how to generate dynamic tokens, see: dynamic token
  • 2: Authentication using third-party webhooks. The CommsEase server does not perform IM login authentication, and the authentication must be performed by a designated third-party server (your app server).

Note that if you use dynamic tokens for authentication, you need to listen to the onwillreconnect callback and set the dynamic token in onwillreconnect

note

For information about how to get tokens and related login methods, see initialization and sign in.

autoMarkRead?: boolean

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.

Associated function

  • MessageInterface.markMsgRead
  • deprecated
    customClientType?: string

    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

    notice

    The default client types are only Web, PC, Android, and iOS. If you need more detailed types, such as WeChat Mini Programs and other platform, map them using this field.

    customTag?: string

    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.

    Associated function

  • NIMGetInstanceOptions.onloginportschange
  • Example

    //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'
    })
    db?: boolean

    Whether to use IM business database (indexedDb), default value: true

    notice

    • Call database operations after onsyncdone ends. Otherwise, the database may not be in service upon calling
    • In the Safari (desktop), and iOS system browser), there are some abnormal problems when using the SDK to operate the database, so the SDK disables the database on the mobile Safari. It is recommended that mobile browsers do not enable the database by default when using the SDK for Web, and set db to false during initialization.
    • On browsers that support databases, the SDK will cache messages, conversations, groups, and other data in the indexedDB database, and subsequent synchronizations will be incrementally updated, speeding up the initial synchronization.

    If you encounter 'not supporting database', 'db::checkDB', 'Not_Support_DB' and other messages during development, please check:

    • Perform the operation that uses the database after the getInstance callback function onsyncdone ends.
    • Make sure you are not using the Safari browser
    dbLog?: boolean

    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.

    note

    The log and the IM business data are stored in two separate databases that do not affect each other.

    debug?: boolean

    Specify whether to print the debugging log.. The default value is false.

    deprecated

    logLevel log level is recommended

    note

    Note that this property only affects whether the console log is enabled, and does not affect the log level stored in indexdb.

    defaultLink?: string

    The default backup address for persistent connection address

    notice

    When requests sent to LBS endpoints fails, NIM SDK will try to connect to this address for persistent connections. If this parameter is unspecified, the address is the public cloud standby address provided by CommsEase.

    expire?: number

    The validity period of logs in the local database. Unit: hour, the default value is 72 hours.

    notice

    This field only takes effect when dbLog is set to true.

    httpsEnabled?: boolean

    Whether the CDN link of the file in the message content is forced to use the HTTPS protocol. The default value is false

    lbsBackup?: boolean

    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.

    lbsBackupUrlsCustomer?: string[]

    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.

    lbsUrl?: string

    LBS addresses are used by default

    notice

    NIM SDK gets endpoints for persistent connection from the LBS address, and establish a persistent connection. If this parameter is unspecified, the address is the public cloud standby address provided by CommsEase.

    logLevel?: "debug" | "info" | "warn" | "error" | "off"

    Log level, the default is off and no log is output. This property affects both indexdb and the log level in the console

    • off: do not output any logs
    • debug: output debug, info, warn and error level logs
    • info: output info, warn, and error level logs
    • warn: output warn and error level logs
    • error: output error level logs
    loginExt?: string

    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.

    note

    For information about third-party webhooks, see Login using third-party callbacks.

    needReconnect?: boolean

    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.

    note

    The interval for reconnection is accumulated from 1.6 to 8s, and each reconnection will trigger the onwillreconnect event.

    nosScene?: string

    Storage scenarios of uploaded files on NOS.

    Notes:

    • For common scenarios, set the storage scenario according to the resource type, and set the scheduled task to delete files.
    • The default storage scenarios for IM: 'im'
    • The default storage scenarios for chat room: 'chatroom'

    Storage scene priority

    • nosScene parameter for sendFile or previewFile
    • the nosScene parameter for initialization
    • Default value: 'im' or 'chatroom'

    Secure links for on-premises applications

    • generate secure links for on-premises applications, set nosScene: '_nim_security'
    • The recipient uses getNosAccessToken to obtain a link with authentication information
    • Authentication information using deleteNosAccessToken is invalid.

    Associated function

    nosSurvivalTime?: number

    The validity period of uploaded files stored on NetEase Object Storage (NOS).

    notice

    default value: Infinity (permanent). The time must not be less than one day, unit: seconds.

    privateConf: { isABTestEnable?: boolean; isDataReportEnable: boolean; isMixStoreEnable: boolean }

    On-premises deployment configuration

    Type declaration

    • Optional isABTestEnable?: boolean

      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

    • isDataReportEnable: boolean

      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

    • isMixStoreEnable: boolean

      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

    quickReconnect?: boolean

    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.

    notice

    This field is only valid when needReconnect is set to true.

    reconnectionAttempts?: number

    The maximum number of retries for reconnection. If the number of retries exceeds the number, the SDK will not try to reconnect again.

    note

    When the maximum number of reconnection attempts is reached, the reconnection process will end, and finally the ondisconnect callback will be triggered.

    resetUnreadMode?: boolean

    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

    • true: continue to reset the unread count of the current client. Note that the unread count displayed locally at this time is different from the unread count on the server
    • false: do not reset reset the unread count of the current client.

    Associated function

    rollbackClearMsgsUnread?: boolean

    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.

    rollbackDelMsgUnread?: boolean

    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.

    Associated function

    deprecated
    secure?: boolean

    Get whether HTTPS is used to connect to the server. The default value is true.

    socketConcurrent?: number

    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.

    syncAvSignal?: boolean

    Whether to synchronize signaling unread messages, default value: true

    Note: supported by SDK v9.10.0 and later

    syncBroadcastMsgs?: boolean

    Whether to synchronize offline broadcast messages during initialization, default value false.

    syncExtraTeamInfo?: boolean

    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:

    • mute: Whether the current member is muted in the group
    • muteNotiType: Group message reminder strategy
    • muteTeam: Whether group mute is enabled
    • nickInTeam: Group nickname
    • invitorAccid: inviter account

    Associated function

  • NIMGetInstanceOptions.onMyTeamMembers
  • syncFriendUsers?: boolean

    Whether to synchronize user profiles during initialization, default value: true

    Associated function

    syncFriends?: boolean
    • whether to sync friends list at initialization, default value: true
    • If the friends list is not synchronized during initialization, you can get the friend list using FriendInterface.getFriends

    Associated function

  • NIMGetInstanceOptions.onfriends
  • syncMsgReceipts?: boolean

    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.

    Associated function

    syncRelations?: boolean

    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.

    syncRoamingMsgs?: boolean

    Whether to synchronize private messages and message history for sync inf advanced groups, the default value is true.

    syncSessionUnread?: boolean

    The default value is false. This parameter has two purposes:

    1. Whether to synchronize the unread count of the conversation during initialization
    2. When the unread count is set at one client, the messages in the conversation are also marked as read on the other clients.

    Associated function

    syncStickTopSessions?: boolean

    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.

    Associated function

    Example

    syncSuperTeamRoamingMsgs?: boolean

    Whether to synchronize the messages for sync in supergroups during initialization, the default value is true.

    syncSuperTeams?: boolean

    Whether to synchronize the supergroup list during initialization, the default value is true

    syncTeams?: boolean
    • Whether to synchronize the list of supergroups during initialization, default value: true.
    • If false, the onteams callback will not be triggered. You can get the list of supergroups by calling TeamInterface.getTeams

    Associated function

  • NIMGetInstanceOptions.onteams
  • token: string

    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).

    Methods

    • Whether to process logs such as log storage, log reporting, etc.

      This function will get parameters for SDK log for use.

      Associated function

      Example

      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}`)
      }
      }
      })

      Parameters

      Returns void

    • onClearServerHistoryMsgs(dataArr: { ext: undefined | string; sessionId: string; time: number }[]): void
    • 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

      Example

      Parameters

      • dataArr: { ext: undefined | string; sessionId: string; time: number }[]

      Returns void

    • onDeleteMsgSelf(data: { custom?: string; deletedTime: number; from: string; idClient: string; idServer: string; scene: "p2p" | "team" | "superTeam"; time: number; to: string }): void
    • Callback invoked when a local message is deleted when the account is logged in on multiple devices.

      Parameters

      • data: { custom?: string; deletedTime: number; from: string; idClient: string; idServer: string; scene: "p2p" | "team" | "superTeam"; time: number; to: string }
        • Optional custom?: string

          Extension field

          Note that the data must be in JSON string

        • deletedTime: number

          Time when a message is deleted

        • from: string

          account of a sender

        • idClient: string

          The message ID generated by the client test can be used as the unique primary key of the message.

        • idServer: string

          The ID used by the server to distinguish messages, used to get message history and keywords for searching message history.

        • scene: "p2p" | "team" | "superTeam"

          Messaging use case:

          • p2p: Private chat
          • team: group chat
          • superteam: supergroup chat
        • time: number

          Timestamp

        • to: string

          ID of a recipient, account ID or group ID

      Returns void

    • onDeleteQuickComment(data: { from: string; idClient: string; idServer: string; scene: "p2p" | "team" | "superTeam"; time: number; to: string }, comment: { body: number; custom?: string; from: string; time: number }): void
    • When deleting a quick comment, the message sender and the logged-in devices of the commenter will get notified by the onDeleteQuickComment callback

      Associated function

      Example

      // 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
      }
      }
      }
      }
      }
      }
      })

      Parameters

      • data: { from: string; idClient: string; idServer: string; scene: "p2p" | "team" | "superTeam"; time: number; to: string }
        • from: string

          account of a sender

        • idClient: string

          The message ID generated by the client test can be used as the unique primary key of the message.

        • idServer: string

          The ID used by the server to distinguish messages, used to get message history and keywords for searching message history.

        • scene: "p2p" | "team" | "superTeam"

          Messaging use case:

          • p2p: Private chat
          • team: group chat
          • superteam: supergroup chat
        • time: number

          Timestamp

        • to: string

          ID of a recipient, account ID or group ID

      • comment: { body: number; custom?: string; from: string; time: number }
        • body: number

          Quick comment

        • Optional custom?: string

          Extension

        • from: string

          ID of the account making the comment.

        • time: number

          time when the comment is posted.

      Returns void

    • onDismissSuperTeam(data: { teamId: string }): void
    • When the group is deleted, all members in the supergroup get notified by onDismissTeam. You can delete a supergroup by calling the server API.

      Example

      const superTeamById = {}

      nim = NIM.getInstance({
      onDismissSuperTeam: function (data) {
      console.log('debug++ onDismissSuperTeam', data)
      const teamId = data.teamId
      delete superTeamById[teamId]
      }
      })

      Parameters

      • data: { teamId: string }
        • teamId: string

      Returns void

    • onDismissTeam(data: { teamId: string }): void
    • (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.

      Parameters

      Returns void

    • (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.

      Parameters

      Returns void

    • onPinMsgChange(data: { msg: NIMMsgPinInfo; pinTag: { createTime: number; pinCustom?: string; pinFrom: string; updateTime: number } }, action: "add" | "update" | "delete"): void
    • When adding, updating, or deleting the PIN tag of a message, the onPinMsgChange callback will be triggered.

      Associated function

      Example

      // 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
      }
      }
      })

      Parameters

      • data: { msg: NIMMsgPinInfo; pinTag: { createTime: number; pinCustom?: string; pinFrom: string; updateTime: number } }
        • msg: NIMMsgPinInfo

          The structure of pinned messages

        • pinTag: { createTime: number; pinCustom?: string; pinFrom: string; updateTime: number }
          • createTime: number
          • Optional pinCustom?: string

            the extension field of PIN messages

          • pinFrom: string

            The user adding the PIN tag to the message

          • updateTime: number
      • action: "add" | "update" | "delete"

      Returns void

    • onQuickComment(msg: { from: string; idClient: string; idServer: string; scene: "p2p" | "team" | "superTeam"; time: number; to: string }, comment: { body: number; custom?: string; from: string; time: number }): void
    • 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.

      Associated function

      Example

      // 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)
      }
      }
      }
      }
      })

      Parameters

      • msg: { from: string; idClient: string; idServer: string; scene: "p2p" | "team" | "superTeam"; time: number; to: string }
        • from: string

          account of a sender

        • idClient: string

          The message ID generated by the client test can be used as the unique primary key of the message.

        • idServer: string

          The ID used by the server to distinguish messages, used to get message history and keywords for searching message history.

        • scene: "p2p" | "team" | "superTeam"

          Messaging use case:

          • p2p: Private chat
          • team: group chat
          • superteam: supergroup chat
        • time: number

          Timestamp

        • to: string

          ID of a recipient, account ID or group ID

      • comment: { body: number; custom?: string; from: string; time: number }
        • body: number

          Quick comment

        • Optional custom?: string

          Custom extension

        • from: string

          ID of the account making the comment.

        • time: number

          time when the comment is posted.

      Returns void

    • onRemoveSuperTeamMembers(data: { account: string[]; team?: NIMSuperTeam; teamId: string }): void
    • When a member leaves the supergroup, all online clients including the client of the member will trigger this callback.

      notice

      You must determine whether the account in the data contains the current IM account (accid) to handle the situation where the current IM account is kicked out of the group.

      Parameters

      • data: { account: string[]; team?: NIMSuperTeam; teamId: string }
        • account: string[]

          Added IM account(accid)

        • Optional team?: NIMSuperTeam

          Group information.

          Note: The team field does not exist for scenarios when a member leaves a group and the onRemoveSuperTeamMembers callback is triggered.

        • teamId: string

          Group ID

      Returns void

    • onRemoveTeamMembers(data: { account: string[]; team?: NIMTeam; teamId: string }): void
    • When a member leaves the group, all online clients including the client of the member will trigger this callback.

      notice

      You must determine whether the account in the data contains the current IM account (accid) to handle the situation where the current IM account is kicked out of the group.

      Associated function

      Example

      Parameters

      • data: { account: string[]; team?: NIMTeam; teamId: string }
        • account: string[]

          Added IM account(accid)

        • Optional team?: NIMTeam

          Group information.

          Note: The team field does not exist for scenarios when a member leaves a group and the onRemoveSuperTeamMembers callback is triggered.

        • teamId: string

          Group ID

      Returns void

    • onSessionsWithMoreRoaming(datas: NIMSession[]): void
    • deprecated

      deprecated

      Hook function - synchronize messages for sync for the conversation during initialization.

      Note: In the time before the session.time, there are still messages that exceed the limit of messages for sync and have not been retrieved. You can enter the conversation and retrieve the message history and messages for sync.

      Parameters

      Returns void

    • Callback invoked when the list of supergroups is synchronized.

      Example

      const superTeamById = {}

      nim = NIM.getInstance({
      syncSuperTeams: true
      onSuperTeams: function (teamArr) {
      for (let team of teamArr) {
      superTeamById[team.teamId] = team
      }
      }
      })

      Parameters

      Returns void

    • The supergroup owner receives the notification when the supergroup is created (supergroups can only be created by calling the server API)

      Parameters

      Returns void

    • onTeamMsgReceipt(data: { teamMsgReceipts: { account: string; idClient: string; idServer: string; read: number; teamId: string; unread: number }[] }): void
    • deprecated.

      NIMGetInstanceOptions.onMsgReceipts is recommended.

      Parameters

      • data: { teamMsgReceipts: { account: string; idClient: string; idServer: string; read: number; teamId: string; unread: number }[] }
        • teamMsgReceipts: { account: string; idClient: string; idServer: string; read: number; teamId: string; unread: number }[]

          data.teamMsgReceipts:

          • teamId: Group ID
          • idServer: idServer of the message
          • idClient: idClient of the message
          • read: The number of accounts that are marked read.
          • unread: The current number of accounts that are not marked read
          • account: The ID of an account marked messages read

      Returns void

    • onTransferTeam(data: { from: { id: string; type: "normal" | "manager" | "owner"; updateTime: number }; team: NIMTeam; to: { id: string; type: "normal" | "manager" | "owner"; updateTime: number } }): void
    • When the ownership of a group changes, all online group members will get notified by this callback

      Associated function

      Parameters

      • data: { from: { id: string; type: "normal" | "manager" | "owner"; updateTime: number }; team: NIMTeam; to: { id: string; type: "normal" | "manager" | "owner"; updateTime: number } }
        • from: { id: string; type: "normal" | "manager" | "owner"; updateTime: number }

          The original owner

          • id: string

            group member ID (group ID + account)

          • type: "normal" | "manager" | "owner"

            Get the type of a group member.

            • 'normal'
            • 'owner'
            • 'manager'
          • updateTime: number

            Get the update time

        • team: NIMTeam
        • to: { id: string; type: "normal" | "manager" | "owner"; updateTime: number }

          The new group owner

          • id: string

            group member ID (group ID + account)

          • type: "normal" | "manager" | "owner"

            Get the type of a group member

            • 'normal'
            • 'owner'
            • 'manager'
          • updateTime: number

            Get the update time

      Returns void

    • onUpdateSuperTeam(data: Pick<NIMSuperTeam, "custom" | "teamId" | "updateTime" | "announcement" | "avatar" | "intro" | "name">): void
    • onUpdateSuperTeamManagers(data: { account: string[]; isManager: boolean; members: Pick<NIMSuperTeamMember, "id" | "updateTime" | "type">[]; team: Pick<NIMSuperTeam, "teamId" | "memberUpdateTime"> }): void
    • When administrators are assigned or unassigned in the supergroup, online group members will get notified by this callback

      Parameters

      • data: { account: string[]; isManager: boolean; members: Pick<NIMSuperTeamMember, "id" | "updateTime" | "type">[]; team: Pick<NIMSuperTeam, "teamId" | "memberUpdateTime"> }
        • account: string[]

          Account to be added

        • isManager: boolean

          Whether the member is administrator

          If false, the administrator is unassigned.

        • members: Pick<NIMSuperTeamMember, "id" | "updateTime" | "type">[]

          Basic info about the member to be assigned administrator.

        • team: Pick<NIMSuperTeam, "teamId" | "memberUpdateTime">

          Group basic info

      Returns void

    • onUpdateSuperTeamMember(data: Pick<NIMSuperTeamMember, "id" | "account" | "custom" | "muteTeam" | "nickInTeam" | "teamId" | "updateTime" | "muteNotiType">): void
    • onUpdateSuperTeamMembersMute(data: { account: string[]; members: Pick<NIMSuperTeamMember, "id" | "teamId" | "updateTime" | "type" | "mute">[]; mute: boolean; team: NIMSuperTeam }): void
    • After the specified member is muted or unmuted, all online members in the supergroup will get notified by this callback

      Parameters

      • data: { account: string[]; members: Pick<NIMSuperTeamMember, "id" | "teamId" | "updateTime" | "type" | "mute">[]; mute: boolean; team: NIMSuperTeam }
        • account: string[]

          Account to be added

        • members: Pick<NIMSuperTeamMember, "id" | "teamId" | "updateTime" | "type" | "mute">[]

          Basic info about the member to be assigned administrator.

        • mute: boolean

          Whether the group is muted.

          If false, the member is unmuted.

        • team: NIMSuperTeam

          Group basic info

      Returns void

    • onUpdateTeamManagers(data: { account: string[]; isManager: boolean; members: { id: string; type: "normal" | "manager" | "owner"; updateTime: number }[]; team: { memberUpdateTime: number; teamId: string } }): void
    • When administrators are assigned or unassigned in the group, online group members will get notified by this callback

      Parameters

      • data: { account: string[]; isManager: boolean; members: { id: string; type: "normal" | "manager" | "owner"; updateTime: number }[]; team: { memberUpdateTime: number; teamId: string } }
        • account: string[]

          Account to be added

        • isManager: boolean

          Whether the member is administrator

          If false, the administrator is unassigned.

        • members: { id: string; type: "normal" | "manager" | "owner"; updateTime: number }[]

          Basic info about the member to be assigned administrator.

        • team: { memberUpdateTime: number; teamId: string }

          Group basic info

          • memberUpdateTime: number

            Group member update timestamp

          • teamId: string

            Group ID

      Returns void

    • onUpdateTeamMembersMute(data: { account: string[]; members: { id: string; mute?: boolean; teamId: string; type: "normal" | "manager" | "owner"; updateTime: number }; mute: boolean; team: NIMTeam }): void
    • After the specified member is muted or unmuted, all online members in the group will get notified by this callback

      Parameters

      • data: { account: string[]; members: { id: string; mute?: boolean; teamId: string; type: "normal" | "manager" | "owner"; updateTime: number }; mute: boolean; team: NIMTeam }
        • account: string[]

          Account to be added

        • members: { id: string; mute?: boolean; teamId: string; type: "normal" | "manager" | "owner"; updateTime: number }

          Basic info about the member to be assigned administrator.

          • id: string

            group member ID (group ID + account)

          • Optional mute?: boolean

            Whether the member is muted

          • teamId: string

            Group ID

          • type: "normal" | "manager" | "owner"

            Get the type of a group member

            • 'normal'
            • 'owner'
            • 'manager'
          • updateTime: number

            Get the update time

        • mute: boolean

          Whether the group is muted.

          If false, the member is unmuted.

        • team: NIMTeam

          Group basic info

      Returns void

    • onblacklist(datas: { account: string; createTime: number; updateTime: number }[]): void
    • 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

      Associated function

      Example

      Parameters

      • datas: { account: string; createTime: number; updateTime: number }[]

      Returns void

    • Callback invoked when broadcast messages are received online. Users can receive one or more broadcast messages online.

      notice

      Broadcast messages are sent only usingServer API.

      Parameters

      Returns void

    • onconnect(data: { connectionId: string; country?: string; customTag?: string; ip: string; lastLoginDeviceId: string; port: string }): void
    • 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:

      • lastLoginDeviceId: The device ID of the last logged-in device
      • customTag: Client-side custom tag, multi-device synchronous change field when logging in, maximum 32 characters
      • connectionId: The connection ID of the current login
      • ip: Client IP address
      • port: Client port number
      • country: The country of this login

      Associated function

      Example

      Parameters

      • data: { connectionId: string; country?: string; customTag?: string; ip: string; lastLoginDeviceId: string; port: string }
        • connectionId: string

          Connection ID of the current login

        • Optional country?: string

          Country

        • Optional customTag?: string

          Client custom tag. Up to 32 characters.

        • ip: string

          Public IP address

        • lastLoginDeviceId: string

          Device ID of the last login

        • port: string

          Port

      Returns void

    • 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.

      Associated function

      notice

      The custom system notification does not exist in the local database, and will be directly transferred without processing.

      Example

      Parameters

      Returns void

    • 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.

      • The SDK is disconnected, and the app can prompt an error message according to the error code, and jump to the login page

      Associated function

      Example

      Example

      // 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");
      }
      })

      Parameters

      Returns void

    • Callback for errors during initialization.

      notice

      The "error" is usually a database error, and also a few connection errors. It is recommended that you collect the errors.

      Parameters

      Returns void

    • 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:

      • the account is already logged in on another devices
      • After login on the current device, the account is logged in or logged out on another device.

      Parameters

      Returns void

    • onmutelist(datas: { account: string; createTime: number; updateTime: number }[]): void
    • 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:

      • When a user in the list sends a message, the message will not be saved for offline messages.
      • The application layer can determine whether to render the notification for unread count according to the list

      Associated function

      Example

      Parameters

      • datas: { account: string; createTime: number; updateTime: number }[]

      Returns void

    • 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.

      Associated function

      notice

      The custom system notification does not exist in the local database, and will be directly transferred without processing.

      Example

      Parameters

      Returns void

    • onofflinemsgs(datas: { msgs: NIMMessage[]; scene: "p2p" | "team" | "superTeam"; sessionId: string; to: string }): void
    • Callback for receiving offline messages during initialization. For more information about the message sources, see the onmsg callback

      notice

      This event will be fired multiple times for synchronization, once for each conversation.

      • Offline messages represents messages that have not been received by any client
      • Messages for sync represents messages received by at least one client

      Associated function

      Example

      Parameters

      • datas: { msgs: NIMMessage[]; scene: "p2p" | "team" | "superTeam"; sessionId: string; to: string }
        • msgs: NIMMessage[]
        • scene: "p2p" | "team" | "superTeam"
        • sessionId: string
        • to: string

      Returns void

    • 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.

      Events for subscription

      1. Online presence status, used to monitor the online presence status of friends. During initialization, the online presence event will only be subscribed the account is online
      • type = 1, value = 1: Online
      • type = 1, value = 2: Logout
      • type = 1, value = 3: Disconnected
      2. Custom events Publish events by calling publishEvent User-defined events must be type = 1, and set a value >= 10000

      Associated function

      Example

      Parameters

      Returns void

    • onroamingmsgs(datas: { msgs: NIMMessage[]; scene: "p2p" | "team" | "superTeam"; sessionId: string; to: string }): void
    • Callback invoked when retrieving messages for sync during initialization. For more information, see onmsg.

      notice

      This event will be fired multiple times for synchronization, once for each conversation.

      • Offline messages represents messages that have not been received by any client
      • Messages for sync represents messages received by at least one client

      Associated function

      Example

      Parameters

      • datas: { msgs: NIMMessage[]; scene: "p2p" | "team" | "superTeam"; sessionId: string; to: string }
        • msgs: NIMMessage[]
        • scene: "p2p" | "team" | "superTeam"
        • sessionId: string
        • to: string

      Returns void

    • onsynccreateteam(data: NIMTeam): void
    • Callback invoked when a group is created for multi-device login.

      deprecated,

      use onCreateTeam

      Parameters

      Returns void

    • onsyncdone(): void
    • 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.

      note

      getHistoryMsgs If the method is called before onsyncdone, the state of the message may be inaccurate. Because the state of the message depends on the read time obtained in synchronization.

      Returns void

    • onsyncfriendaction(data: { account?: string; friend?: NIMFriendProfile; type: "addFriend" | "applyFriend" | "passFriendApply" | "rejectFriendApply" | "deleteFriend" | "updateFriend" }): void
    • onsyncmarkinblacklist(data: { account: string; isAdd: boolean; record: { account: string; updateTime: number } }): void
    • Callback for synchronizaing the blocklist during initialization

      Associated function

      Example

      Parameters

      • data: { account: string; isAdd: boolean; record: { account: string; updateTime: number } }
        • account: string

          Target account ID

        • isAdd: boolean

          Whether the account is included in the blocklist or the list of muted members.

          true: Yes, false: No.

        • record: { account: string; updateTime: number }

          Details of the operation record

          • account: string

            Target account ID

          • updateTime: number

            Update timestamp

      Returns void

    • onsyncmarkinmutelist(data: { account: string; isAdd: boolean; record: { account: string; updateTime: number } }): void
    • The callback for synchronizing "the blocklist and list of muted users" across devices.

      Associated function

      Example

      Parameters

      • data: { account: string; isAdd: boolean; record: { account: string; updateTime: number } }
        • account: string

          Target account ID

        • isAdd: boolean

          Whether the account is included in the blocklist or the list of muted members.

          true: Yes, false: No.

        • record: { account: string; updateTime: number }

          Details of the operation record

          • account: string

            Target account ID

          • updateTime: number

            Update timestamp

      Returns void

    • 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:

      • total = friend + msg + team + superTeam
      • msg = deleteMsg
      • friend = applyFriend + passFriendApply + rejectFriendApply + deleteFriend
      • team = applyTeam + rejectTeamApply + teamInvite + rejectTeamInvite
      • superTeam = applySuperTeam + rejectSuperTeamApply + superTeamInvite + rejectSuperTeamInvite

      For functions that trigger system notifications, see onsysmsg

      Associated function

      Parameters

      Returns void

    • 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:

      • total = friend + msg + team + superTeam
      • msg = deleteMsg
      • friend = applyFriend + passFriendApply + rejectFriendApply + deleteFriend
      • team = applyTeam + rejectTeamApply + teamInvite + rejectTeamInvite
      • superTeam = applySuperTeam + rejectSuperTeamApply + superTeamInvite + rejectSuperTeamInvite

      For functions that trigger system notifications, see onsysmsg

      Associated function

      Parameters

      Returns void

    • onupdateteammember(data: Pick<NIMTeamMember, "id" | "account" | "custom" | "muteTeam" | "nickInTeam" | "teamId" | "updateTime" | "muteNotiType">): void
    • onwillreconnect(data: { duration: number; retryCount: number }): void
    • 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.

      notice

      If this callback is triggered, the SDK has disconnected from the CommsEase server for a long time. The app prompts on the interface: the app is disconnected, and reconnecting.

      notice

      If authType is set to 1, you must dynamically update the token for onwillreconnect. For an asynchronous scenario, such as waiting for the server to respond, you can return a Promise, and the SDK will wait for the Promise to complete before reconnecting

      Example

      Parameters

      • data: { duration: number; retryCount: number }
        • duration: number

          retry interval

        • retryCount: number

          number of retries

      Returns void

    • shouldCountNotifyUnread(notification: NIMMessage): void
    • 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.

      notice

      This method receives a notification. If the function returns true, the notification will be included in the unread count, otherwise it will not be counted into the unread count. Returns false by default.

      Example

      NIM.getInstance({
      shouldCountNotifyUnread: function(msg) {
      // Assume that in your business scenario, when removing group members, there is no need to set the unread count of the conversation.
      return msg && msg.attach && msg.attach.type !== "removeTeamMembers"
      }
      })

      Parameters

      Returns void

    • shouldIgnoreNotification(notification: NIMMessage): void
    • Determine whether to ignore notification messages Notification messages include group notification messages and supergroup notification messages, see NIMGetInstanceOptions.onmsg.

      notice

      This method receives a notification message and returns a boolean value. This default value is false.

      Example

      NIM.getInstance({
      shouldIgnoreNotification: function(msg) {
      // Assume that in your business scenario, when removing group members, the last message of the group is not required
      return msg && msg.attach && msg.attach.type !== "removeTeamMembers"
      }
      })

      Parameters

      Returns void