---
source_url: https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/links
title: Links
updated_at: 2026-06-15T12:11:33.310Z
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Links

Encode URLs (`www`, `http`, `https`) as clickable links or create hyperlinks with custom text.

:::tip Generic referencing
Channel references, user mentions, and links share the same `MessageElement` structure with different `MentionTarget` values.
:::

## Add links

`addMention()` adds a link to a [draft message](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/drafts).

### Method signature

Call `addMention()` with `target` set to `MentionTarget.Url`. See [addMention()](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/drafts#add-message-element) for details.

### Sample code

Create the `Hello Alex! I have sent you this link on the #offtopic channel.` message where `link` is a URL.

```kotlin
// create an empty message draft
val messageDraft = channel.createMessageDraft(isTypingIndicatorTriggered = channel.type != ChannelType.PUBLIC)

// add the text
messageDraft.update(text = "Hello Alex! I have sent you this link on the #offtopic channel.")

// add a link to the string 'link'
messageDraft.addMention(offset = 33, length = 4, target = MentionTarget.Url(url = "www.pubnub.com"))
```

## Remove links

`removeMention()` removes a link from a [draft message](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/drafts).

### Method signature

Call `removeMention()` at the exact offset where the link starts. See [removeMention()](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/drafts#remove-message-element) for details.

:::warning Offset value
If you don't provide the position of the first character of the message element to remove, it isn't removed.
:::

### Sample code

Remove the link from the `Hello Alex! I have sent you this link on the #offtopic channel.` message where `link` is a URL.

```kotlin
// assume the message reads
// Hello Alex! I have sent you this link on the #offtopic channel.`

// remove the link mention
messageDraft.removeMention(offset = 33)
```

## Get link suggestions

The message elements listener returns link suggestions that match the 3-letter string in the draft.

:::note Single listener
The message elements listener returns suggested mentions for channel references, user mentions, and links.
:::

### Method signature

Add a message elements listener to receive link suggestions. See [addChangeListener()](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/messages/drafts#add-message-draft-change-listener) for details.

### Sample code

```kotlin
// create a message draft
val messageDraft = channel.createMessageDraft(isTypingIndicatorTriggered = channel.type != ChannelType.PUBLIC)

// add the listener
val listener = { elements: List<MessageElement>, suggestedMentions: PNFuture<List<SuggestedMention>> ->
        updateUI(elements) // updateUI is your own function for updating UI
        suggestedMentions.async { result ->
            result.onSuccess { updateSuggestions(it) } // updateSuggestions is your own function for displaying suggestions
        }
    }
messageDraft.addChangeListener(listener)
```

## Get text links

`getMessageElements()` returns URLs as link elements in published messages. Customize rendering with your own functions. This method also handles [mention rendering](https://www.pubnub.com/docs/chat/kotlin-chat-sdk/build/features/users/mentions#show-mention-as-link).

### Method signature

This method has the following signature:

```kotlin
message.getMessageElements(): List<MessageElement>
```

#### Input

This method doesn't take any parameters.

#### Output

| Type | Description |
| --- | --- |
| `List<MessageElement>` | A list of message elements representing parsed components of the input text, including processed user mentions, links, and referenced channels based on the available data. |

##### MessageElement details

Each `MessageElement` on the returned list can be of one of these types:

* `data class PlainText(override val text: String) : MessageElement`
* `data class Link(override val text: String, val target: MentionTarget) : MessageElement`

If a `MessageElement` is of type `Link`, its `target` depends on the returned item:

```kotlin
// Mentioned user identified by [userId].
data class User(val userId: String) : MentionTarget

// Referenced channel identified by [channelId].
data class Channel(val channelId: String) : MentionTarget

// Link to [url].
data class Url(val url: String) : MentionTarget
```

### Sample code

Get all text links included in the message with the `16200000000000000` timetoken.

```kotlin
chat.getChannel("incident-management").async { channelResult ->
    channelResult.onSuccess { channel ->
        // Successfully retrieved the channel
        channel?.getMessage(16200000000000000L)?.async { messageResult ->
            messageResult.onSuccess { message ->
                // Handle success
                val elements = message?.getMessageElements()

                // Find and print all text links in the message elements
                val textLinks = elements?.filter { it is Link && it.target is Url }
                
                if (!textLinks.isNullOrEmpty()) {
                    println("Text links in the message:")
                    textLinks.forEach { link ->
                        println(link) // Print or process each text link as required
                    }
                } else {
                    println("No text links found in the message.")
                }
            }.onFailure { error ->
                // Handle failure
                println("Failed to retrieve the message: ${error.message}")
            }
        }
    }.onFailure { error ->
        // Failed to retrieve the channel
        println("Failed to retrieve the channel: ${error.message}")
    }
}
```

## Get text links (deprecated)

`textLinks` returns all text links in a message.

### Method signature

This is how you can access the property:

```kotlin
message.textLinks
```

### Sample code

Get all text links included in the message with the `16200000000000000` timetoken.

```kotlin
val channel = chat.getChannel("your-channel")

channel.getMessage(16200000000000000).async { result ->
    result.onSuccess { message: Message? ->
        if (message != null) {
            // Access the textLinks property
            val textLinks = message.textLinks
            
            if (textLinks != null && textLinks.isNotEmpty()) {
                println("The message contains the following text links:")
                textLinks.forEach { textLink ->
                    println("Link: ${textLink.link}, Start Index: ${textLink.startIndex}, End Index: ${textLink.endIndex}")
                }
            } else {
                println("The message does not contain any text links.")
            }
        } else {
            println("Message does not exist")
        }
    }.onFailure { exception: PubNubException ->
        println("Exception occurred: ${exception.message}")
    }
}
```