How to show hyperlink in LWC toast

I have created a LWC that executes a call to the controller and shows a toast message if the call fails:

 const event = new ShowToastEvent({
                    title: "Error",
                    message: "An error has occured. Return to record.",
                    variant: "error"
                  });
 this.dispatchEvent(event);

Return to record should be a hyperlink. Still, if I build the message to include the hyperlink, the string gets escaped and the hyperlink doesn’t get properly displayed.
I have checked the documentation and couldn’t find a way to do that, even though in aura it was available.

Is there any way to achieve this? Or it’s simply not supported yet?


Edit:
I have managed to include a Return to Record link in the toast using Jayant’s answers below. Here is the code that does that:

AuraContainer.cmp:

<aura:component implements="lightning:isUrlAddressable,force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId">
    <c:sendemail onshowtoast="{!c.handleShowToast}"/>
</aura:component>

AuraContainer.js:

({
    handleShowToast : function(component, event, helper) {
        var message = event.getParam('message');
        var sObjectEvent = $A.get("e.force:navigateToSObject");
        var toastEvent = $A.get("e.force:showToast");

        toastEvent.setParams({
            title: message.title,
            mode: message.mode,
            type: message.variant,
            message: 'Sample Message', // you will need to keep this attribute, even though it's not used
            messageTemplate: '{0} {1}',
            messageTemplateData: [
                message.text,
                {
                    url: '',
                    label: 'Return to Org',
                    executionComponent: {
                        descriptor: "markup://force:navigateToSObject",
                                        attributes: {recordId: message.recordId, slideDevName:"detail"},
                                        isEvent: true,
                                        isClientSideCreatable: true,
                                        componentName: 'navigateToSObject'

                    }
                }
            ]
        });
        toastEvent.fire();
    }
})

SendEmail LWC:

import { LightningElement, api, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';
import checkOrgValidity from '@salesforce/apex/SendEmailController.checkOrgValidity'
import { ShowToastEvent } from 'lightning/platformShowToastEvent'

export default class SendEmail extends LightningElement {
    @api recordId;

    // Injects the page reference that describes the current page
    @wire(CurrentPageReference)
        currentPageReference;

    async connectedCallback() {
        this.recordId = this.currentPageReference.state.c__recordId;

        checkOrgValidity({sId: this.recordId})
                    .then(result => {
                        // processing in case of success                           
                    })
                    .catch(error => {
                        var errors = JSON.parse(error.body.message);
                        for(var i = 0; i < errors.length; i++) {
                            // make sure that the message is not empty
                            if(errors[i]) {
                                this.showToastWithHyperlink(errors[i], this.recordId, 'Warning', 'warning', 'sticky');
                            }
                        }
                    });
    }

    showToastWithHyperlink(msg, recordId, title, variant, mode) {
        let message = {};
        message.title = title;
        message.text = msg;
        message.recordId = recordId;
        message.mode = mode;
        message.variant = variant;

        const showToast = new CustomEvent('showtoast', {
            detail: { message },
        });

        this.dispatchEvent(showToast);
    }
}

The Lightning component gets opened using a Detail Page Button:

Behavior: Display in existing window with sidebar
Button or Link URL: /lightning/cmp/c__SendEmailContainer?c__recordId={!Account.Id}

Answer

UPDATE [July 8, 2020]

LWC now supports showing hyperlinks in the toast message.

This seems to have been introduced in last couple of months as commented on the idea that I had created at the time of writing this answer first. The implementation details/example is documented, excerpt below.

Displaying Links in Toasts

To display a link in the message, use the messageData attribute to pass in url and label values for the message string.

const event = new ShowToastEvent({
    "title": "Success!",
    "message": "Record {0} created! See it {1}!",
    "messageData": [
        'Salesforce',
        {
            url: 'http://www.salesforce.com/',
            label: 'here'
        }
    ]
});

As of today, it doesn’t seem you can use links in toast message in LWC directly. I have created this idea to allow the ability to show links in LWC toasts.

In Lighting Aura Components (LAC), the force:showToast had additional attributes for this purpose – messageTemplate and messageTemplateData.

But, these attributes are not available for the corresponding LWC lightning-platform-show-toast-event. Even if you try using it there, it does not have an impact.


Your option here is as Pranay mentioned in the comments, you can utilize a Custom Event in your LWC and then wrap your LWC in a LAC which handles the event and takes care of raising the toast message.

Here’s a sample code how you can use it.

From LWC, raise a Custom Event:

showNotification() {
    let myData = [];
    myData[0] = "Title of Message";
    myData[1] = "This message is from LWC";
    myData[2] = "https://linktomyrecord.com";
    const showToast = new CustomEvent('showtoast', {
        detail: { myData },
    });

    this.dispatchEvent(showToast);
}

Then, in your Lightning Aura Component, include the LWC:

<c:lwcAuraComponent onshowtoast="{!c.handleShowToast}"/>

And then in handleShowToast(), get the values and raise the toast message. (Note that, you will still need to keep the message attribute in the event)

handleShowToast : function(component, event, helper) {
    var myData = event.getParam('myData');

    var title = myData[0];
    var msg = myData[1];
    var linkToRec = myData[2];
    
    var toastEvent = $A.get("e.force:showToast");
    toastEvent.setParams({
        mode: 'pester', // or 'dismissible' -- see docs for details
        title: title,
        message: 'Sample Message', // you will need to keep this attribute
        messageTemplate: 'Record {0} created! See it {1}!',
        messageTemplateData: [
            msg, 
            {
                url: linkToRec, // here's your link
                label: 'here',
            }
        ]
    });
    toastEvent.fire();
} 

Attribution
Source : Link , Question Author : Teodora , Answer Author : Jayant Das

Leave a Comment