Initialize SDK

Update time: 2024/03/14 18:45:31

Please refer to Integration mode > Introduce SDK to download and introduce SDK file. For complete configuration file of initialization, see API Document.

Sample codes

javascriptvar data = {};
// If the incoming SDK file is NIM_Web_NIM_v.js, please initialize the file with NIM.getInstance; If the incoming SDK file is NIM_Web_SDK_v, please initialize the file with SDK.NIM.getInstance. For information on the SDK files, see integration methods.
var nim = NIM.getInstance({
  debug: true, // Whether to enable logs and print logs to console. We recommend doing so during the integration development.
  appKey: 'appKey',
  account: 'account',
  token: 'token',
  db:true, //If the data base is not required, set the value as false. By default, the SDK sets the value as true.
  // privateConf: {}, // Configurations required for private deployment
  onconnect: onConnect,
  onwillreconnect: onWillReconnect,
  ondisconnect: onDisconnect,
  onerror: onError
});
function onConnect() {
  console.log('connected successfully');
}
function onWillReconnect(obj) {
  // The `SDK` has been disconnected. So, the developer needs to inform the users that it is disconnected and connection is being re-established on The API.
  console.log('Reconnect immediately');
  console.log(obj.retryCount);
  console.log(obj.duration);
}
function onDisconnect(error) {
  // The `SDK` is disconnected. And the developer should give the appropriate error message based on the specific error code, and open the login page.
  console.log('connection lost');
  console.log(error);
  if (error) {
    switch (error.code) {
      // Wrong account or password. Please jump to the login page and prompts the error.
      case 302:
        break;
      // Repeat login. Please jump to the login page and prompts the error.
      case 417:
        break;
      // Removed. Please jump to the login page after prompting the error.
      case 'kicked':
        break;
      default:
        break;
    }
  }
}
function onError(error) {
  console.log(error);
}

Parameter description

  • debug: It determines whether to enable logs. Developers can enable the log feature, so that the SDK will print key operation information to console for debugging.
  • logFunc: Log analysis function. By default, CommsEase SDK can enable developers to print logs to console. But it is inconvenient to track and query errors for mobile devices, hybrid app and the like. The SDK provides a configuration parameter logFunc which can capture log information and input it to user custom function (SDK also provides plugin for developers' reference). The auxiliary development implements secondary processing for information in hybrid app/PC client/mobile explorer.
  • appKey: appKey can be viewed at CommsEase console.
  • account: An unique account in the app.
  • token: token of account, used for creating connection.
  • customTag: Client custom tag, with max size 32 characters.
  • transports: It is used to create protocol array of long connection. It can be empty and default value is ['websocket', 'xhr-polling'].
    • By default, sdk prefers to websocket connection. If the explorer does not support websocket, xhr-polling is used.
    • Developers can set connection and sequence manually. The available options include websocket, xhr-polling and flashsocket.
    • Example: transports: ['websocket'、'xhr-polling'、'flashsocket']
  • keepNosSafeUrl: It determines whether to keep secure short link of files on NOS unchanged. The value is false by default. The short link is replaced with source link automatically. If it is set to true, short link is kept and users can change it with The API Replace short link of files on NOS with source link.
  • rollbackDelMsgUnread: It determines whether to revoke influenced unread count when revoked message is received. The value is false by default. It determines whether revoked messages are included in unread count. If it is set to true, 1 will be deducted from unread count at the revocation under unread scene of revoked message.
  • noCacheLinkUrl: It means not to cache link address. The value is false by default. If it is set to true, new link address is acquired from lbs address every time when re-connection is tried.
  • privateConf: Required configuration for private configuration. The related js file can be configured and downloaded at management console to introduce related content to configuration.
  • onconnect: It is a callback after creating connection (successful login), which will input an object, including login information, with fields as below:
    • lastLoginDeviceId: Last login device ID
    • customTag: Client custom tag
    • connectionId: Connection ID of the login
    • ip: Client IP
    • port: Client port
    • country: Country of the login
  • onwillreconnect: A callback for re-connection
    • SDK has been disconnected, developers shall inform the users that it is disconnected and connection is being re-established.
    • The callback will get an object which includes extra information, with fields shown as below:
      • duration: Time until next re-connection
      • retryCount: Retry count
  • ondisconnect: Callback after disconnection
    • Now, SDK is disconnected. Developers shall prompt related error information based on error code and skip to login page.
    • The callback will get an object which includes error information, with fields shown as below:
      • code: Error code for any error. It may be empty.
        • 302: Error account password. Please skip to login page and prompt error.
        • 417: Repeated login. You have logged in at other clients. Please skip to login page and prompt error.
        • 'kicked': Kicked out
  • onerror: It is a callback of an error, error object will be input.

Synchronization completed

SDK will notify developers after completing synchronization. Developers can initialize The API and execute other operations after the callback is returned. The synchronized data includes:

  • Blacklist, with corresponding callback onblacklist. Please refer to initialization parameter in User relationship hosting.
  • Mute list, with corresponding callback onmutelist. Please refer to initialization parameter in User relationship hosting.
  • Friends, with corresponding callback onfriends. Please refer to initialization parameter in Host friends.
  • My card, with corresponding callback onmyinfo. Please refer to initialization parameter in Host user profile.
  • Friend card, with corresponding callback onusers. Please refer to initialization parameter in Host user profile.
  • Team, with corresponding callback onteams. Please refer to initialization parameter in Group features.
  • Session, with corresponding callback onsessions. Please refer to initialization parameter in Recent session.
  • Roaming messages, with corresponding callback onroamingmsgs. Please refer to initialization parameter in Receive and send message.
  • Offline messages, with corresponding callback onofflinemsgs. Please refer to initialization parameter in Receive and send message.
  • Offline system notification, with corresponding callback onofflinesysmsgs. Please refer to initialization parameter in System notification.
  • Offline custom system notification, with corresponding callback onofflinecustomsysmsgs. Please refer to initialization parameter in System notification.

Sample codes

javascriptvar nim = NIM.getInstance({
  onsyncdone: onSyncDone
});
function onSyncDone() {
  console.log('synchronization completed');
}

Initialize configuration (synchronization protocol)

  • SDK synchronizes following parameters by default, but will not synchronize other parameters:
    • syncRelations: Synchronize user relationship
    • syncFriends: Synchronize friends
    • syncFriendUsers: Synchronize the list of user cards corresponding to friends
    • syncRoamingMsgs: Synchronize roaming message (offline message will be pushed automatically, so that there is no need to enable it)
    • syncMsgReceipts: Synchronize acknowledged receipt of message
    • syncTeams:Synchronize team
    • syncExtraTeamInfo: Synchronize extra team profile

Developers can select data for synchronizing or not synchronizing configurable data. These are initialization parameters.

All configurable synchronization parameters include:

  • syncRelations: It determines whether to synchronize blacklist and mute list. The value is true by default. If it is false, blacklist and mute list cannot be received, i.e. the callback onblacklist and onmutelist will not be returned. Developers can invoke The API Get a blocklist and mute list to get a blocklist and mute list later.
  • syncFriends: It determines whether to synchronize the list of friends. The value is true by default. If it is false, the callback onfriends cannot be triggered. Developers can invoke The API Get friends list to get the list of friends.
  • syncFriendUsers: It determines whether to synchronize the list of user cards corresponding to friends. The value is true by default. If it is false, the callback onusers cannot be triggered.
  • syncTeams: It determines whether to synchronize the list of teams. The value is true by default. If it is false, the list of teams cannot be received, i.e. the callback onteams cannot be triggered. Developers can invoke The API Get teams list to get the list of teams.
  • syncExtraTeamInfo: It determines whether to synchronize extra team profile. The default true is to synchronize extra team profile. Now, it includes that
    • The current login user enables message tip of a team (SDK only stores the information, while developers control detailed usage of the information).
    • The API Update my team attribute is invoked to disable or enable message tip of a team.
    • The API Need team message tip can be invoked to query that team message tip is required.
  • syncTeamMembers, Deprecated: determines whether to synchronize team members and are removed after v4.4.0. The value is true in v4.2.0 and above and false in v4.3.0 and later. They can play a role only when syncTeams=true is true. If the value is false, they will not synchronize team members, i.e. the callback onteammembers and onsyncteammembersdone will not be returned. Developers can invoke The API Get team members to get team members as required.
  • syncRoamingMsgs: It determines wether to synchronize roaming message, with default value true. If it is false, roaming message cannot be received, i.e. the callback onroamingmsgs will not be returned.
  • syncMsgReceipts: It determines whether to synchronize timestamp of acknowledged receipt. The value is true by default. If it is false, the timestamp of acknowledged receipt cannot be received.
  • syncBroadcastMsgs: It determines whether to synchronize broadcast message. The value is false by default.
  • syncSessionUnread: It determines whether to synchronize unread count of sessions (It is valid when database is enabled to ensure consistent unread count at multiple devices).

Sample codes

javascriptvar nim = NIM.getInstance({
  syncRelations: false,
  syncBroadcastMsgs: true,
  onsyncRelationsdone: function(err, obj) {
    // ....
  }
});

Configuration for initialization (other protocols)

  • debug: It determines whether to enable log, with parameter "true/false". Developers can enable log feature, so that SDK will print key operation information to console for debugging.
  • db: It determines whether to enable local database for storing data, with parameter "true/false". The indexedDb is used.
  • nosScene: nos storage scene. The value is im by default.
  • nosSurvivalTime: Valid time of nos storage scene. The value is Infinity by default.
  • uploadUrl/downloadUrl: Special API of private deployment solution for processing file. Please refer to Preview universal method of images.
  • enabledHttpsForMessage: It is designed based on iOS requirements for https link. If it is set to "true", the link of all file messages will be changed to https. Now, link of all files that are uploaded by CommsEase sdk is https. There is not need for developers to pay attention to The API.
  • needReconnect: It determines whether to re-connect automatically if connection is failed.
  • autoMarkRead: It determines whether to automatically mark received message as "acknowledged".
  • shouldIgnoreNotification: It is a function which indicates to neglect a certain message of notification type. The API will filter received notification messages based on upper-defined logics. If "true" is returned, SDK will neglect the notification message.
  • shouldCountNotifyUnread: The parameter type is function. It determines whether to add unread count button for team message tip. The upper developers analyze the object of callback parameter. If "true" is returned, team message tip is included in unread count, otherwise, it is not included.
  • ntServerAddress: Report address for connection statistics. If it is empty, connection statistics will not be reported and users can fill in their log report address; otherwise, statistical address of CommsEase server is the default address.

Log analysis

  • The SDK provides initialization parameters which can assist users to collect log information and make further analysis. For example, in hybrid apps, users even can input js-bridge to collect logs.
  • An example is that mobile app reports logs to server for analysis.
javascript// client code
// logger plug-in
function LoggerPlugin(options) {
  var logLevelMap = {
    debug: 0,
    log: 1,
    info: 2,
    warn: 3,
    error: 4
  };
  var self = this;
  var postUrl = options.url || empty;
  self.level = logLevelMap[options.level] || 0;
  self.logCache = [];
  self.logNum = 1;
  self.timeInterval = 5000;
  window.onerror = function(
    errorMessage,
    scriptURI,
    lineNumber,
    columnNumber,
    errorObj
  ) {
    self.error.call(self, errorObj);
  };
  setInterval(function() {
    if (self.logCache.length > 0 && postUrl) {
      self.postLogs(postUrl, self.logCache);
    }
  }, self.timeInterval);
}

LoggerPlugin.prototype.debug = function() {
  if (this.level > 0) {
    return;
  }
  console.debug.apply(this, arguments);
  this.cacheLogs.apply(this, ['[degbug]'].concat(arguments));
};

LoggerPlugin.prototype.log = function() {
  if (this.level > 1) {
    return;
  }
  console.log.apply(this, arguments);
  this.cacheLogs.apply(this, ['[log]'].concat(arguments));
};

LoggerPlugin.prototype.info = function() {
  if (this.level > 2) {
    return;
  }
  console.info.apply(this, arguments);
  this.cacheLogs.apply(this, ['[info]'].concat(arguments));
};

LoggerPlugin.prototype.warn = function() {
  if (this.level > 3) {
    return;
  }
  console.warn.apply(this, arguments);
  this.cacheLogs.apply(this, ['[warn]'].concat(arguments));
};

LoggerPlugin.prototype.error = function() {
  if (this.level > 4) {
    return;
  }
  console.error.apply(this, arguments);
  this.cacheLogs.apply(this, ['[error]'].concat(arguments));
};

LoggerPlugin.prototype.cacheLogs = function(logLevel, args) {
  var currentCache = [];
  for (var i = 0; i < args.length; i++) {
    var arg = args[i];
    if (typeof arg === 'object') {
      currentCache.push(JSON.stringify(arg));
    } else {
      currentCache.push(arg);
    }
  }
  var logStr = this.logNum++ + ' ' + logLevel + ' ' + currentCache.join('; ');
  this.logCache.push(logStr.replace('%c', ''));
};

LoggerPlugin.prototype.postLogs = function(url, data) {
  var self = this;
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      if (xhr.status === 200) {
        console.info('LoggerPlugin:: log reporting completed’);
        self.logCache = [];
        self.timeInterval = 5000;
      } else {
        self.timeInterval += 5000;
      }
    }
  };
  xhr.open('POST', url);
  xhr.setRequestHeader('Content-Type', 'plain/text;charset=utf-8');
  xhr.timeout = 360;
  xhr.send(data.join('\n'));
};
  • The SDK can also integrate LoggerPlugin code. Users can use NIM.LoggerPlugin to invoke. We recommend referring to codes for some advanced developments.
javascript// client code
var nim = NIM.getInstance({
  debug: true,
  logFunc: new LoggerPlugin({
    url: '/getlogger',
    level: 'info'
  })
});
  • Here, nodejs + express is used as server and related server codes are written for reference only.
javascript// server code
const express = require('express');
const fs = require('fs');
const app = express();

app.post('/getlogger', (req, res) => {
  req.setEncoding('utf8');
  req.rawBody = '';
  req.on('data', chunk => {
    req.rawBody += chunk;
  });
  req.on('end', () => {
    let body = req.rawBody;
    fs.appendFile('sdklog.log', body, () => {
      res.end();
    });
  });
});

Complete initialization codes

javascript    var data = {};
    var nim = NIM.getInstance({
        // Initialize the SDK
        // debug: true
        appKey: 'appKey',
        account: 'account',
        token: 'token',
        customTag: 'TV',
        onconnect: onConnect,
        onerror: onError,
        onwillreconnect: onWillReconnect,
        ondisconnect: onDisconnect,
        // multi-device login
        onloginportschange: onLoginPortsChange,
        // User relationship
        onblacklist: onBlacklist,
        onsyncmarkinblacklist: onMarkInBlacklist,
        onmutelist: onMutelist,
        onsyncmarkinmutelist: onMarkInMutelist,
        // friendship
        onfriends: onFriends,
        onsyncfriendaction: onSyncFriendAction,
        // user profile
        onmyinfo: onMyInfo,
        onupdatemyinfo: onUpdateMyInfo,
        onusers: onUsers,
        onupdateuser: onUpdateUser,
        // team
        onteams: onTeams,
        onsynccreateteam: onCreateTeam,
        onUpdateTeam: onUpdateTeam,
        onteammembers: onTeamMembers,
        // onsyncteammembersdone: onSyncTeamMembersDone,
        onupdateteammember: onUpdateTeamMember,
        // team message read notification
        onTeamMsgReceipt: onTeamMsgReceipt,
        // session
        onsessions: onSessions,
        onupdatesession: onUpdateSession,
        // Message
        onroamingmsgs: onRoamingMsgs,
        onofflinemsgs: onOfflineMsgs,
        onmsg: onMsg,
        // system notification
        onofflinesysmsgs: onOfflineSysMsgs,
        onsysmsg: onSysMsg,
        onupdatesysmsg: onUpdateSysMsg,
        onsysmsgunread: onSysMsgUnread,
        onupdatesysmsgunread: onUpdateSysMsgUnread,
        onofflinecustomsysmsgs: onOfflineCustomSysMsgs,
        oncustomsysmsg: onCustomSysMsg,
        // receive broadcast message
        onbroadcastmsg: onBroadcastMsg,
        onbroadcastmsgs: onBroadcastMsgs,
        // synchronization completed
        onsyncdone: onSyncDone
    });

    function onConnect() {
        console.log('connected successfully');
    }
    function onWillReconnect(obj) {
        // The `SDK` has been disconnected, and the developer should inform the users that it is disconnected and connection is being re-established on The API.
        console.log('Reconnect immediately');
        console.log(obj.retryCount);
        console.log(obj.duration);
    }
    function onDisconnect(error) {
        // The `SDK` is disconnected, and the developer should give the appropriate error message based on the error code, and jump to the login page.
        console.log('connection lost');
        console.log(error);
        if (error) {
            switch (error.code) {
            // Wrong account or password. Please jump to the login page and prompt an error.
            case 302:
                break;
            // Removed. Please jump to the login page after prompting an error.
            case 'kicked':
                break;
            default:
                break;
            }
        }
    }
    function onError(error) {
        console.log(error);
    }

    function onLoginPortsChange(loginPorts) {
        console.log('The status of the current login account has changed on the other client', loginPorts);
    }

    function onBlacklist(blacklist) {
        console.log('receive blacklist', blacklist);
        data.blacklist = nim.mergeRelations(data.blacklist, blacklist);
        data.blacklist = nim.cutRelations(data.blacklist, blacklist.invalid);
        refreshBlacklistUI();
    }
    function onMarkInBlacklist(obj) {
        console.log(obj);
        console.log(obj.account + 'other client' + (obj.isAdd ? 'add' : 'remove') + 'blacklist');
        if (obj.isAdd) {
            addToBlacklist(obj);
        } else {
            removeFromBlacklist(obj);
        }
    }
    function addToBlacklist(obj) {
        data.blacklist = nim.mergeRelations(data.blacklist, obj.record);
        refreshBlacklistUI();
    }
    function removeFromBlacklist(obj) {
        data.blacklist = nim.cutRelations(data.blacklist, obj.record);
        refreshBlacklistUI();
    }
    function refreshBlacklistUI() {
        // Refresh The API
    }
    function onMutelist(mutelist) {
        console.log('receive mute list', mutelist);
        data.mutelist = nim.mergeRelations(data.mutelist, mutelist);
        data.mutelist = nim.cutRelations(data.mutelist, mutelist.invalid);
        refreshMutelistUI();
    }
    function onMarkInMutelist(obj) {
        console.log(obj);
        console.log(obj.account + 'inactively' + (obj.isAdd ? 'added' : 'removed') + 'mute list');
        if (obj.isAdd) {
            addToMutelist(obj);
        } else {
            removeFromMutelist(obj);
        }
    }
    function addToMutelist(obj) {
        data.mutelist = nim.mergeRelations(data.mutelist, obj.record);
        refreshMutelistUI();
    }
    function removeFromMutelist(obj) {
        data.mutelist = nim.cutRelations(data.mutelist, obj.record);
        refreshMutelistUI();
    }
    function refreshMutelistUI() {
        // Refresh The API
    }

    function onFriends(friends) {
        console.log('receive friends list', friends);
        data.friends = nim.mergeFriends(data.friends, friends);
        data.friends = nim.cutFriends(data.friends, friends.invalid);
        refreshFriendsUI();
    }
    function onSyncFriendAction(obj) {
        console.log(obj);
        switch (obj.type) {
        case 'addFriend':
            console.log('you added a friend at other devices' + obj.account + ', postscript' + obj.ps);
            onAddFriend(obj.friend);
            break;
        case 'applyFriend':
            console.log('you applied to add a friend at other devices' + obj.account + ', postscript' + obj.ps);
            break;
        case 'passFriendApply':
            console.log('you passed a friend application at other devices' + obj.account + ', postscript' + obj.ps);
            onAddFriend(obj.friend);
            break;
        case 'rejectFriendApply':
            console.log('you rejected a friend application at other devices' + obj.account + ', postscript' + obj.ps);
            break;
        case 'deleteFriend':
            console.log('you deleted a friend at other devices' + obj.account);
            onDeleteFriend(obj.account);
            break;
        case 'updateFriend':
            console.log('you updated a friend at other devices', obj.friend);
            onUpdateFriend(obj.friend);
            break;
        }
    }
    function onAddFriend(friend) {
        data.friends = nim.mergeFriends(data.friends, friend);
        refreshFriendsUI();
    }
    function onDeleteFriend(account) {
        data.friends = nim.cutFriendsByAccounts(data.friends, account);
        refreshFriendsUI();
    }
    function onUpdateFriend(friend) {
        data.friends = nim.mergeFriends(data.friends, friend);
        refreshFriendsUI();
    }
    function refreshFriendsUI() {
        // Refresh The API
    }

    function onMyInfo(user) {
        console.log('receive my profile', user);
        data.myInfo = user;
        updateMyInfoUI();
    }
    function onUpdateMyInfo(user) {
        console.log('My profile is updated', user);
        data.myInfo = NIM.util.merge(data.myInfo, user);
        updateMyInfoUI();
    }
    function updateMyInfoUI() {
        // Refresh The API
    }
    function onUsers(users) {
        console.log('remove user profile list', users);
        data.users = nim.mergeUsers(data.users, users);
    }
    function onUpdateUser(user) {
        console.log('user profile is updated', user);
        data.users = nim.mergeUsers(data.users, user);
    }
    function onTeams(teams) {
        console.log('team list', teams);
        data.teams = nim.mergeTeams(data.teams, teams);
        onInvalidTeams(teams.invalid);
    }
    function onInvalidTeams(teams) {
        data.teams = nim.cutTeams(data.teams, teams);
        data.invalidTeams = nim.mergeTeams(data.invalidTeams, teams);
        refreshTeamsUI();
    }
    function onCreateTeam(team) {
        console.log('you created a team', team);
        data.teams = nim.mergeTeams(data.teams, team);
        refreshTeamsUI();
        onTeamMembers({
            teamId: team.teamId,
            members: owner
        });
    }
    function refreshTeamsUI() {
        // Refresh The API
    }
    function onTeamMembers(teamId, members) {
        console.log('team id', teamId, 'team members', members);
        var teamId = obj.teamId;
        var members = obj.members;
        data.teamMembers = data.teamMembers || {};
        data.teamMembers[teamId] = nim.mergeTeamMembers(data.teamMembers[teamId], members);
        data.teamMembers[teamId] = nim.cutTeamMembers(data.teamMembers[teamId], members.invalid);
        refreshTeamMembersUI();
    }
    // function onSyncTeamMembersDone() {
    //     console.log('synchronization of team list completed');
    // }
    function onUpdateTeam (team) {
        console.log('update team status', team)
    }
    function onUpdateTeamMember(teamMember) {
        console.log('team member information is updated', teamMember);
        onTeamMembers({
            teamId: teamMember.teamId,
            members: teamMember
        });
    }
    function refreshTeamMembersUI() {
        // Refresh The API
    }
    function onTeamMsgReceipt (teamMsgReceipts) {
        console.log('team message read notification', teamMsgReceipts)
    }

    function onSessions(sessions) {
        console.log('Receive session list', sessions);
        data.sessions = nim.mergeSessions(data.sessions, sessions);
        updateSessionsUI();
    }
    function onUpdateSession(session) {
        console.log('session is updated', session);
        data.sessions = nim.mergeSessions(data.sessions, session);
        updateSessionsUI();
    }
    function updateSessionsUI() {
        // Refresh The API
    }

    function onRoamingMsgs(obj) {
        console.log('roaming message', obj);
        pushMsg(obj.msgs);
    }
    function onOfflineMsgs(obj) {
        console.log('offline message', obj);
        pushMsg(obj.msgs);
    }
    function onMsg(msg) {
        console.log('receive message', msg.scene, msg.type, msg);
        pushMsg(msg);
    }
    function onBroadcastMsg(msg) {
        console.log('receive broadcast message', msg);
    }
    function onBroadcastMsgs(msgs) {
        console.log('receive broadcast message list', msgs);
    }
    function pushMsg(msgs) {
        if (!Array.isArray(msgs)) { msgs = [msgs]; }
        var sessionId = msgs[0].sessionId;
        data.msgs = data.msgs || {};
        data.msgs[sessionId] = nim.mergeMsgs(data.msgs[sessionId], msgs);
    }

    function onOfflineSysMsgs(sysMsgs) {
        console.log('receive offline system message’, sysMsgs);
        pushSysMsgs(sysMsgs);
    }
    function onSysMsg(sysMsg) {
        console.log('receive system notification', sysMsg)
        pushSysMsgs(sysMsg);
    }
    function onUpdateSysMsg(sysMsg) {
        pushSysMsgs(sysMsg);
    }
    function pushSysMsgs(sysMsgs) {
        data.sysMsgs = nim.mergeSysMsgs(data.sysMsgs, sysMsgs);
        refreshSysMsgsUI();
    }
    function onSysMsgUnread(obj) {
        console.log('receive system notification unread', obj);
        data.sysMsgUnread = obj;
        refreshSysMsgsUI();
    }
    function onUpdateSysMsgUnread(obj) {
        console.log('system notification unread is updated', obj);
        data.sysMsgUnread = obj;
        refreshSysMsgsUI();
    }
    function refreshSysMsgsUI() {
        // Refresh The API
    }
    function onOfflineCustomSysMsgs(sysMsgs) {
        console.log('receive offline custom system notification', sysMsgs);
    }
    function onCustomSysMsg(sysMsg) {
        console.log('receive custom system notification', sysMsg);
    }

    function onSyncDone() {
        console.log('synchronization completed');
    }

Clear singleton instance

web SDK connection instances are set as singleton mode, but related API can be invoked to clear instances in memory. Namely, connection is disabled to clear message history and timestamp in memory, so that developers can re-connect clearly.

javascript  var nim = NIM.getInstance({...})
  // Clear an instance
  nim.destroy({
    done: function (err) {
      console.log('instance has been fully cleared')
    }
  })

** Notes:**

  • After The API nim.disconnect() or nim.destroy() is invoked manually, The API ondisconnect of instance will be triggered, but now websocket is not destroyed. Only when the callback done is returned, status of socket can be onclose.
  • This is especially important in WeChat applet, because there are only two available websocket in applet. If the previous socket is not closed, socket resource will be occupied, resulting in repeated re-connection or kick-out.
Was this page helpful?
Yes
No
  • Sample codes
  • Parameter description
  • Synchronization completed
  • Initialize configuration (synchronization protocol)
  • Configuration for initialization (other protocols)
  • Log analysis
  • Complete initialization codes
  • Clear singleton instance