Skip to main content

Custom Message

In addition to using the built-in message types provided by the SDK, developers can also define custom message types based on their business requirements.

warning
  • Custom message types must be registered before sending and receiving such messages.
  • It is recommended to consolidate all custom message registration operations between the init method and the connect method for easier management and maintenance.
  • The message type name and message structure of custom messages must remain consistent across all platforms (including mobile, web, etc.), otherwise message interoperability will fail.
  • Do not use "RC:" as a prefix for custom message type names to avoid conflicts with built-in SDK message types.

Registering Custom Messages

Use the RongIMLib.registerMessageType method to register custom message types. The method returns the constructor function corresponding to the message type.

Interface

RongIMLib.registerMessageType(messageType, isPersited, isCounted, searchProps, isStatusMessage)

Parameter Description

ParameterTypeRequiredDescription
messageTypeStringYesMessage type name, must be consistent across platforms
isPersitedBooleanYesWhether to store the message
isCountedBooleanYesWhether to count the message
searchPropsstring[]YesSearchable fields of the message. Not required for web. For numeric fields, the value range is (-2^64, 2^64) and must be an integer
isStatusMessageBooleanNoWhether it is a status message. Status messages are not stored or counted, and are only received when the recipient is online

Example Code

const PersonMessage = RongIMLib.registerMessageType('s:person', true, true, [], false)

Sending Custom Messages

Custom messages can be sent using the SDK's sendMessage method.

Example Code

// Construct the custom message to be sent
const message = new PersonMessage({ name: 'someone', age: 18 })


// Send the message
RongIMLib.sendMessage({
conversationType: RongIMLib.ConversationType.PRIVATE,
targetId: '<targetId>'
}, message).then(res => {
if (res.code === 0) {
console.log(res.code, res.data)
} else {
console.log(res.code)
}
})