Browse SDKs · HarmonyOS
Platform
SDKsHarmonyOSEnterprise

Load message context

Retrieve surrounding chat messages before and after a specific anchor message.

Copy

When jumping into chat context from search results or replied quotes, use the complete fetched message as the anchor.

Code example

import sdk, {
  FetchSurroundingMessagesReq,
  FetchSurroundingMessagesResp,
  ViewType,
} from '@openimsdk/imsdk';

const request: FetchSurroundingMessagesReq = {
  startMessage: targetMessage,
  viewType: ViewType.ViewHistory,
  before: 20,
  after: 20,
};
const response: FetchSurroundingMessagesResp = await sdk.fetchSurroundingMessages(request);
renderMessages(response.messages);

Parameters

ParameterTypeRequiredDescription
startMessageIMMessageYesAnchor message object around which surrounding history is retrieved.
viewTypeViewTypeYesView mode, typically ViewType.ViewHistory.
beforenumberYesNumber of messages to retrieve chronologically before the anchor.
afternumberYesNumber of messages to retrieve chronologically after the anchor.

Return value

Returns a Promise resolving to FetchSurroundingMessagesResp:

PropertyTypeDescription
messagesIMMessage[]Array of chronologically ordered surrounding messages including the anchor.

State changes after the call

Returned message counts may be fewer than before + after if the anchor is near timeline boundaries or if intermediate messages have been deleted. The anchor message must come from query results or message events; do not construct incomplete objects. When merging with existing lists, deduplicate by conversation context and clientMsgID. For ongoing pagination forward or backward, see Load older messages and Load newer messages.