Skip to main content

JavaScript Functions Reference

REQUIREMENTS

All functions are available via the global BetterMessages object. Add your code to a custom JavaScript file enqueued after Better Messages, or use inline <script> tags.

This page lists all public JavaScript functions available in the Better Messages plugin. Use these to programmatically control the messaging UI.


Initialization#

BetterMessages.initialize()#

Initializes all Better Messages related elements on the page that were not initialized before. Useful for dynamic elements added after page load.

Returns: true

// After dynamically adding messaging elements to the page
BetterMessages.initialize();

Conversations#

BetterMessages.openChatWithUser( userId )#

Opens a private conversation with the specified user. If a conversation already exists, it opens it; otherwise creates a new one.

Parameters:

  • userId (number) — User ID to open conversation with
var user_id = 3;
BetterMessages.openChatWithUser( user_id );

BetterMessages.openUniqueConversation( key )#

Opens or creates a conversation identified by a unique key. For guests, triggers guest authentication first. Opens the conversation in a mini chat.

Parameters:

  • key (string) — Unique conversation identifier
BetterMessages.openUniqueConversation( 'order-123-support' );

Full Screen#

BetterMessages.openFullScreen()#

Immediately opens the full-screen user inbox. On mobile-enabled sites, opens the mobile view instead.

BetterMessages.openFullScreen();

Mini Chats#

BetterMessages.miniChatOpen( threadId, open )#

WebSocket Version

This functionality is available only with the WebSocket version.

Opens a mini chat widget for the specified thread. Mini chats are small floating chat windows fixed to the bottom of the screen. The open parameter controls whether the chat window starts expanded or minimized.

Parameters:

  • threadId (number) — Conversation ID to open
  • open (boolean, optional) — Whether to expand the chat window. Default true
var thread_id = 10;
var open = true;
BetterMessages.miniChatOpen( thread_id, open );

BetterMessages.miniChatClose( threadId )#

WebSocket Version

This functionality is available only with the WebSocket version.

Closes the mini chat widget for the specified thread and removes it from the screen. The thread remains accessible — it can be reopened at any time.

Parameters:

  • threadId (number) — Conversation ID to close
var thread_id = 10;
BetterMessages.miniChatClose( thread_id );

BetterMessages.openNewConversationWidget()#

WebSocket Version

This functionality is available only with the WebSocket version.

When mini chats are active — opens a mini widget to create a new conversation. If mini chats are not active — redirects to the new conversation screen at the messages page.

BetterMessages.openNewConversationWidget();

Online Users#

BetterMessages.getOnlineUsers()#

WebSocket Version

This functionality is available only with the WebSocket version.

Returns an array of user IDs that are currently online. Only available with WebSocket version — requires an active connection to the presence system. The list updates in real-time as users connect and disconnect.

Returns: array — Array of online user IDs

var onlineUsers = BetterMessages.getOnlineUsers();
console.log( 'Online users:', onlineUsers );

Call Status#

BetterMessages.isInCall()#

WebSocket Version

This functionality is available only with the WebSocket version.

Returns whether the current user is currently in an active voice or video call. Useful for preventing conflicting actions or showing call status indicators in custom UI elements.

Returns: boolean

if ( BetterMessages.isInCall() ) {
console.log( 'User is in a call' );
}

Group Calls#

BetterMessages.getGroupCallParticipants( threadId )#

WebSocket Version

This functionality is available only with the WebSocket version.

Returns how many people are in a conversation's group call right now. The answer comes over the WebSocket connection the page already holds, so it costs your own server nothing — no WordPress request, no database read. This is the right way to show a live "3 people in the room" count beside a Join button.

Group video and group audio are separate rooms, so both counts come back and a conversation can have people in each at the same time.

Parameters:

  • threadId (number | number[]) — a conversation ID, or an array of them

Returns: Promise{ video, audio } for a single ID, or an object keyed by conversation ID when you pass an array

const counts = await BetterMessages.getGroupCallParticipants( 123 );

document.querySelector( '#room-123-count' ).textContent = counts.video;

Pass an array to price a whole directory of rooms in one round trip:

const rooms = await BetterMessages.getGroupCallParticipants( [ 123, 124, 125 ] );

Object.entries( rooms ).forEach( ( [ threadId, counts ] ) => {
console.log( threadId, counts.video, counts.audio );
} );

To keep a number on screen current, subscribe to better_messages_group_call_status rather than calling this on a timer — the server pushes when the count changes.

Both counts are 0 when no call is running, and when the page has no WebSocket connection — which is the case for a visitor who is neither logged in nor registered through guest chat.


BetterMessages.subscribeGroupCallStatus( threadId )#

WebSocket Version

This functionality is available only with the WebSocket version.

Watches one or more conversations and receives their participant counts as they change, through better_messages_group_call_status. Use this for a room the visitor has not joined — a public page advertising a chat room, or a directory listing a room and its overflow room.

The call server pushes on change, so nothing polls and your own server is never involved.

Parameters:

  • threadId (number | number[]) — a conversation ID, or an array of them

Returns: Promise<boolean>true once the subscription is live

await BetterMessages.subscribeGroupCallStatus( [ 123, 124 ] );

wp.hooks.addAction( 'better_messages_group_call_status', 'my_plugin', function( threadId, counts ) {
document.querySelector( '#room-' + threadId + '-count' ).textContent = counts.video;
} );

Subscribing also delivers the current counts straight away, so a page does not need a separate read to paint its first value, and a client that was offline heals by subscribing again.

Requires a chat connection

Counts travel over the visitor's own chat connection, which exists for a logged-in member and for a visitor already registered through guest chat. A visitor who is neither has no connection, so this resolves false and the counts read as 0. On a fully public page, make sure guest chat is enabled if anonymous visitors need to see the number.


BetterMessages.unsubscribeGroupCallStatus( threadId )#

WebSocket Version

This functionality is available only with the WebSocket version.

Stops watching one or more conversations. Call it when the element showing the count is removed from the page.

Parameters:

  • threadId (number | number[]) — a conversation ID, or an array of them
BetterMessages.unsubscribeGroupCallStatus( 123 );

BetterMessages.openGroupCall( threadId, type )#

WebSocket Version

This functionality is available only with the WebSocket version.

Takes the member straight into one conversation's group call from anywhere on the site. The conversation opens full screen and the call is joined for them, so a "Join Room" button on an ordinary page needs no messenger on that page at all. Pair it with subscribeGroupCallStatus to send people to whichever room has space.

Whoever arrives first opens the call and everyone after joins it. When a room is set to let only moderators start a call, a member still joins a call that is already running.

Parameters:

  • threadId (number) — the conversation ID
  • type (string, optional)'video' (default) or 'audio'

Returns: Promise<boolean>true once the call has been joined

document.querySelector( '#join-crafting-room' ).addEventListener( 'click', async function () {
await BetterMessages.openGroupCall( 123 );
} );

The conversation opens either way. The promise resolves false when the call itself could not be joined — group calls switched off for that room, or a member without permission — leaving them in the room, where they can still read and write.



WebSocket#

BetterMessages.getSocket()#

WebSocket Version

This functionality is available only with the WebSocket version.

Returns the raw socket.io client instance for advanced integrations. Use this to listen to custom socket events, emit custom data, or check connection state. Returns null if WebSocket is not connected.

Returns: Socket|null

var socket = BetterMessages.getSocket();
if ( socket ) {
console.log( 'Socket connected:', socket.connected );
}

API Access#

BetterMessages.getApi()#

Returns the internal API instance for making direct REST API calls to Better Messages endpoints. The promise waits for the client-side database to be fully initialized before resolving, ensuring all dependencies are ready.

Returns: Promise<object> — The API instance

var api = await BetterMessages.getApi();
// Use api to make custom API calls

Thread Management#

BetterMessages.updateThreadsLists()#

Forces a refresh of the threads list in the UI by triggering the threads list update observable. Use this after programmatically modifying threads (creating, deleting, or updating) to ensure the UI reflects the changes.

// After programmatically modifying threads
BetterMessages.updateThreadsLists();

BetterMessages.resetMainVisibleThread()#

Resets the currently visible thread on the main screen, returning the user to the threads list view. Dispatches a better-messages-main-screen-change custom DOM event. Useful for programmatic navigation when you need to close the current conversation.

BetterMessages.resetMainVisibleThread();

Settings Storage#

BetterMessages.getDbSetting( key, standard )#

Retrieves a setting value from the client-side IndexedDB/SQLite database. Returns the standard default value if the setting hasn't been stored yet. Settings persist across page reloads and browser sessions.

Parameters:

  • key (string) — Setting key
  • standard (any, optional) — Default value if setting is not found

Returns: Promise<any>

var value = await BetterMessages.getDbSetting( 'my_custom_setting', 'default' );

BetterMessages.updateSetting( key, value )#

Stores a setting value in the client-side IndexedDB/SQLite database. The value persists across page reloads and browser sessions. Use this for custom user preferences that should survive page navigation.

Parameters:

  • key (string) — Setting key
  • value (any) — Value to store

Returns: Promise

await BetterMessages.updateSetting( 'my_custom_setting', 'new_value' );

BetterMessages.deleteSetting( key )#

Removes a setting from the client-side IndexedDB/SQLite database permanently. After deletion, getDbSetting() for this key will return the default value.

Parameters:

  • key (string) — Setting key to remove

Returns: Promise

await BetterMessages.deleteSetting( 'my_custom_setting' );

Utility#

BetterMessages.parseHash()#

Parses URL hash variables to handle deep links and navigation parameters. Call this after programmatically changing the URL hash to trigger Better Messages navigation logic (e.g., opening a specific thread or view).

// After programmatically changing the URL hash
BetterMessages.parseHash();