Instant Messaging
Web
Quick Start
Product Introduction
Overview
Features
Limits
Features
Account integration and login
Messaging
Team Chat
Chat Room
Chat Room Tags
Multi-device Login
Statistics Monitoring
Development Integration
Integration
Initializing the SDK
Login and Logout
Messaging
Recent Chats
User Profile Hosting
Friends Data Hosting
User Relationship Data Hosting
Online Status Subscription
Message History
System Notification
Team
Superteam
Chat Room
High availability of domain name
Extension Features
Tools
API Reference
Status Code

Integration

Update time: 2021/12/06 16:35:37

CommsEaseJavaScript SDK(Web-SDK) provides complete IM development features for PC/Mobile Web apps, Node.js, React Native, WeChat Mini Program, ByteDance, and other cross-platform apps which can shield internal complex details and provide a simple API API for the third-party apps to fast integrate IM features.

Web-SDK browser environment is compatible with mainstream desktop browsers such as IE9+ (IE10 and later for audio and video), Edge, Chrome 58+, Safari 10+, Firefox 54+; Compatible with smartphones of iPhone 5s and later (iOS 8.0+) and built-in WeChat browser; Chrome browser for mainstream Android 5+ system and built-in WeChat browser.

Web-SDK cross-platform environment supports many scene apps, for example, WeChat Mini Program/ByteDance Microapp, React Native, Node.js.

Select the SDK

  • If you use IM feature only, you need to introduce NIM_Web_NIM_*.jsand initialize IM instance with NIM.getInstance({...}).

  • If you use Chat room feature only, you need to introduceNIM_Web_Chatroom_*.jsand initialize chat room instance with Chatroom.getInstance({...}) .

  • If you use IM and chat room features, you need to introduce NIM_Web_SDK_*.jsand initialize IM and chat room instance with SDK.NIM.getInstance({...}) and SDK.Chatroom.getInstance({...}).

Integration at browser environment

Please visit SDK download page to get Web-SDK of the latest browser environment.

Notes: CommsEase Web IM SDK is compatible with IE9+ (v5.0.0 and earlier versions are available to IE8). IE8/IE9 can be connected to CommsEase server only when the project is deployed under HTTPS environment. Other advanced browsers can be connected to CommsEase IM server under HTTP or HTTPS environment.

Integration at cross-platform environment

The operation method of cross-platform features related API from CommsEase Web-SDK is basically the same with JavaScript invoking mode under browser environment, which can reduce learning costs for users. Definitely, SDK will also make some adaptations based on some differences among different platforms, for example, "use database", "upload file", "restrict WebSocket", etc.

Applet

Applet overview

Please visit SDK download page to get Web-SDK of the latest applet.

  • WeChat Mini Program: Available fromv5.1.0.
  • ByteDance Microapp: Available fromv7.8.0.

The global variable is "window" for browser environment and "wx" for applet, so that they have different attributes. To implement compatibility and adaptability, SDK will mock some attributes (e.g. navigator, location, io) to global, which will not influence ordinary application of users.

The number of WebSocket connections

WeChat Mini Program v1.7.0 and later allow maximum 5 WebSocket connections. Therefore, connection count must be controlled when multiple sockets are used.

When users switch account and use new instance of chat room, in order not to exceed limitation of applet WS connection, they must executedestroyof IM/chat room instance and then try new connection in callbackdone.

A whitelist of domain names

A list of related configurations:

  • Legal domain name of request:

    • https://lbs.netease.im
    • https://wlnimsc0.netease.im (required for IM)
    • https://wlnimsc1.netease.im (required for chat room)
  • Legal domain name of socket:

    • wss://wlnimsc0.netease.im (required for IM)
    • wss://wlnimsc1.netease.im (required for chat room)
  • Legal domain name of uploadFile:

    • https://nos.netease.com (required for uploading file, for example, sending file message)
  • Legal domain name of downloadFile:

    • https://nim-nosdn.netease.im (required for downloading CommsEase resource file, for example, downloading audio file)

React Native

React Native overview

From v5.3.0, CommsEase Web-SDK is adaptive to React Native. RN version >=0.51 is recommended. The operation method of most APIs of CommsEase WebSDK React Native (hereinafter referred to as "RN-SDK") is same with Web browser environment for SDK in order to reduce obstacles resulting from using SDK by developers.

For information on related SDK files, contact CommsEase technical support.

Local database

RN-SDK supports the mode of application with and without database. You can select independently based on service scene of developers.

  • If database is not used,dbshall be set tofalseat the operation of IM initialization, for example:
  const nim = NIM.getInstance({
    debug: true,
    appKey: appKey,
    account: account,
    token: token,
    db: false,  // don't use database
    onconnect: onConnect,
    onwillreconnect: onWillReconnect,
    ondisconnect: onDisconnect,
    onerror: onError
  });
  • If the database is used, developers shall install realm. It's available to usesqlite3as local database although RN-SDK currently does not support it. You can plug in SDK instance to database withusePluginas below:
  const SDK = require('NIM_Web_SDK_vx.x.x.js');
  const Realm = require('realm');
  // The external realm database is mounted to the sdk for use
  SDK.usePlugin({
    db: Realm,
  });
  const nim = SDK.NIM.getInstance({
    debug: true,
    appKey: appKey,
    account: account,
    token: token,
    db: true,   // use database
    onconnect: onConnect,
    onwillreconnect: onWillReconnect,
    ondisconnect: onDisconnect,
    onerror: onError
  });

Local log

RN-SDK supports storing logs locally and and remote acquire logs remotely. Developers can select to enable local log feature as required.

After enabling local log feature, the SDK will write logs to user devices (mobile phone) in the form of file. When users are online, they can invoke the server API to get logs on user client for troubleshooting.

Local storage depends on the library react-native-fs, with steps as below:

  1. Install react-native-fs
npm install react-native-fs --save
  1. Plug in database to SDK with usePlugin as below:
const RNFS = require('react-native-fs');

const params = {
  rnfs: RNFS
};
params.rnfs.size = 1024 * 1024;  // maximum log file size, unit: bytes; optional, 1M by default
SDK.usePlugin(params);

const nim = SDK.NIM.getInstance({
  // .....
  // initialize IM
});

Message push

From V5.3.0, message push is provided. When configuring a project, developers need to introduce related Android and APNs dependence.

  • APNs

    • For APNs configuration, developers shall visit Apple website for applying for certificate with the push feature.
    • After configuring a certificate, they shall add related features as per RN push configuration.
  • Android push

If push is not required parametersiosPushConfigandandroidPushConfigshall not be passed in.

Sample codes:

  // iOS/Android external push code
  const iosPushConfig = {
    tokenName: 'push_online',
  };
  const androidPushConfig = {
    xmAppId: '2882303106219',
    xmAppKey: '59717219',
    xmCertificateName: 'RN_MI_PUSH',
    hwCertificateName: 'RN_HW_PUSH',
    mzAppId: '11398',
    mzAppKey: 'b74148973e60a2af4c2f6779',
    mzCertificateName: 'RN_MZ_PUSH',
    fcmCertificateName: 'RN_FCM_PUSH',
    vivoCertificateName: "vivopush",
    oppoAppId: "xxx", // oppoAppId, oppoAppKey, oppoAppSercet are available by registering with oppo push platform
    oppoAppKey: "xxx",
    oppoAppSercet: "xxx",
    oppoCertificateName: "oppopush"
  };
  var nim = SDK.NIM.getInstance({
    // ...
    iosPushConfig,
    androidPushConfig,
    // ...
  })

  // Android internal push example code, not remote push
  import { showNotification } from '../nim/NIM_Android_Push';
  showNotification({
    icon: '', title: msg.from, content: showText, time: `${msg.time}`,
  });

Send files

We do not recommend sending files with The APIsendFile, but get file handle withpreviewFile, add other file attributes to file object by other api methods, and finally send file with The APIsendFile, because RN-SDK requires to get attributes of file message and sends them together with file message. An example of sending image files:

  nim.previewFile({
    type: 'image',
    filePath: options.filePath,
    maxSize: maxSize,
    commonUpload: true,
    uploadprogress(obj) {
      // ...
    },
    done: (error, file) => {
      // Image attributes such as length, width,and size can be obtained using other API APIs
      file.w = options.width;
      file.h = options.height;
      file.MD5 = options.MD5;
      file.size = options.size;
      const { scene, to } = options;
      if (!error) {
        constObj.nim.sendFile({
          type: 'image',
          scene,
          to,
          file,
          done: (err, msg) => {
            if (err) {
              return;
            }
            this.appendMsg(msg);
          },
        });
      }
    },
  });
  • List of extra attached attributes required for message:
    • Image object
      • size: Size, unit: byte
      • MD5: Value after transforming image file MD5
      • w: Width, unit: px
      • h: Height, unit: px
    • Audio object
      • size: Size, unit: byte
      • MD5: Value after transforming audio file MD5
      • dur: Length, unit: ms
    • Video object
      • size: Size, unit: byte
      • MD5: Value after transforming video file MD5
      • w: Width, unit: px
      • h: Height, unit: px
      • dur: Length, unit: ms
    • File object
      • size: Size, unit: byte
      • MD5: Value after transforming file MD5

Node.js

Node.js Overview

From v5.6.0, CommsEase WebSDK is designed to adapt node.js, so that IM app scene can be extended to server with Node.js environment. The node.js solution can be used to scenes of Server-as-a-Client and Client-as-a-Server, for example, linux industrial control, chatbot, data pipeline, standalone monitoring, scale data analysis.

The global variable is "window" for browser environment and "global" for node.js, so that they have different attributes. To implement compatibility and adaptability, SDK will mock some attributes (e.g. Navigator, location, WebSocket) to global, which will not influence ordinary application of users.

For information on related SDK files, contact CommsEase technical support.

Local database

Due to a variety of storage systems in server environment, the SDK will not integrate database, and users can use data storage services such as mysql, oracle, ms-sql, sqlite, mongodb, and hbase independently. When using node.js sdk, users can still enable server-api features of CommsEase to process server data to save time.

Send files

Please use the parameterfilePathto upload Node.js.

  nim.previewFile({
    type: 'image',
    maxSize: maxSize,
    commonUpload: true,
    filePath: options.filePath,
    uploadprogress(obj) {
      // ...
    },
    done: (error, file) => {
      const { scene, to } = options;
      if (!error) {
        constObj.nim.sendFile({
          type: 'image',
          scene,
          to,
          file,
          done: (err, msg) => {
            if (err) {
              return;
            }
            this.appendMsg(msg);
          },
        });
      }
    },
  });

Log record

The SDK supports to using the third-party log recording tool to help users record logs at server in the form of file log. Here is an example of third-party librarynpm-log4js 3.*for log recording.

  • Initializationlog4js:
  const log4js = require('log4js');
  log4js.configure({
    replaceConsole: true,
    appenders: { nimlog: { type: 'file', filename: 'nim-debug.log' } },
    categories: { default: { appenders: ['nimlog'], level: 'ALL' } }
  });
  const logger = log4js.getLogger('nimlog');
  • Method of introducing log plug-in in IM and chat room:
  global.nim = NIM.getInstance({
    debug: true,
    logFunc: logger,
    // ...
  })

How can I introduce the SDK

How can I introduce script

The required SDK file is input to src with script tag.The SDK can be introduced by the attribute of window object hereinafter.

<!-- Example -->
<script src="NIM_Web_SDK_vx.x.x.js">
<script>
  var nim = SDK.NIM.getInstance({
    // ...
  })
</script>

Introduce import/require

In browser framework and cross-platform environment, SDK can be introduced by import/require.

Notes: If developers select webpack/babel to pack, please use "exclude" to excluse SDK files to avoid error due to second packing of babel.

Example of SDK invocation in project:

  // Example
  import SDK from 'NIM_Web_SDK_vx.x.x.js'
  const nim = SDK.NIM.getInstance({
    // ...
  })

Related Webpack configurations:

  // Webpack reference configuration
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /NIM_Web_SDK_vx.x.x.js/,
        query: {
          presets: [
            // ...
          ],
          // ...
        }
        // ...
      },
      // ...
    ],
    // ...
  }

Instructions

Instance invocation mode

All services can be invoked by NIM SDK singleton, for example:

  // After introducing a reference to the SDK class, get the SDK instance
  var nim = SDK.NIM.getInstance({
    debug: true,
    appKey: appKey,
    account: account,
    token: token,
    // ...
  });

Sending peer-to-peer messages is taken for an example:

  var msg = nim.sendText({
    scene: 'p2p',
    to: account,
    text: 'hello',
    done: function sendMsgDone (error, msg) {
      // ...
    }
  });

Event notification mode

The SDK notifies API invoking results to upper-level developers by callback and "delegate". The two methods are triggered on the main thread only (To ensure browser compatibility, web worker is not used.)

  • Generally, callback APIs are reflected in the parameter done of corresponding APIs and can be set when they are called.
  • In the "Delegate" mode, the developers need to handle the initialized asynchronous listener function at a proper time.
  // Delegate a notification example
  var nim = NIM.getInstance({
    // ... Other configurations are omitted
    onmsg: function (msg) {
      // Here is a delegate message event. After a message is sent successfully, the message is also processed here
    }
  });


  // Callback notification event
  var msg = nim.sendText({
    scene: 'p2p',
    to: account,
    text: 'hello',
    done: function sendMsgDone (error, msg) {
      // Here is a callback message event that simply informs the developer whether The message is sent successfully.
    }
  });
Was this topic helpful?
Yes
No
  • Select the SDK
  • Integration at browser environment
  • Integration at cross-platform environment
  • Applet
  • Applet overview
  • The number of WebSocket connections
  • A whitelist of domain names
  • React Native
  • React Native overview
  • Local database
  • Local log
  • Message push
  • Send files
  • Node.js
  • Node.js Overview
  • Local database
  • Send files
  • Log record
  • How can I introduce the SDK
  • How can I introduce script
  • Introduce import/require
  • Instructions
  • Instance invocation mode
  • Event notification mode