Level up your Twilio API skills in TwilioQuest, an educational game for Mac, Windows, and Linux. Download Now

Menu

Expand
Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Notifications Framework

Notifications Framework provides a client-side API to manage notifications in Flex UI

What is a notification in Flex?

A notification is an alert that tells the user what state change or error has occurred to a component or page when they are no longer viewing that component or page

Users can be notified in Flex using a Notification Bar or Browser notifications or both.

What are notification framework capabilities?

  • Register custom notifications including browser notifications
  • Customize standard notifications
  • Turn off standard UI notifications
  • Override standard notifications per Task Channel Definition
  • Customize how standard UI notifications are displayed
  • Register your custom UI notifications and specify how to render them

NotificationsBar

NotificationBar is an in-app way to alert user. NotificationBar has a variety of options like icon, actions, timeout. Learn more in Notification Object properties

Screenshot 2019-10-07 at 20.17.12.png

Browser Notifications

We are using the standard Browser Notification API for Flex Notifications Framework browser notifications implementation.

Browser notifications are shown if Flex is not in focus or is minimized.

Requesting permissions

To start showing browser notifications user needs to first grand permissions. By default, Flex will request user for permissions if they are not granted or blocked.

If you want to add custom logic around requesting permissions, like request it based on some user action in the UI, then you can dispatch Notification.requestPermission() from your custom code.

Available methods of Notification Framework

Method Description
registerNotification(notification: Notification) Register a custom notification
showNotification(id: string, context?: Object): Notification Dispatch a notification
dismissNotification(notification: Notification) Dismiss a notification
dismissNotificationById(id: string) Dismiss a notification by Id
dismissAll() Dismiss all notifications
registerHandler(handler)

Register notification handler. Use to expose your notification handler.

isNotificationHandlerEnabled()

Returns whether the notification handler for the given id is enabled or not

toggleNotificationHandler(id, enabled)

Enable or disable notification handler

Available handlers:

  • browser
  • inapp

Property Type Description
id string

notification Id

Must be unique. An error will be thrown if another notification is already registered with the same id.

content string | React.ReactChild | React.ReactElement<NotificationContentProps> content of the notification. Can be a text, a template or custom React component
type string

notification type. Possible values:

information = "information",
success = "success",
warning = "warning",
error = "error"

backgroundColor? string background color for notification bar
icon? string notification icon for notification bar
timeout? number

time in milliseconds that notification bar is visible before automatically dismissed; default is 3000 milliseconds; if set to 0, the notification bar will not be automatically dismissed

closeButton? boolean if set to false, the notification bar will not have a close button to be dismissed manually
context? object context variables that can be used in content templates.
isApplicable callback function callback determining whether particular notification instance should be shown
options object

Options for the notification handlers

Available options - browser notifications handler (add link)

actions
Array<React.ReactElement>

List of custom clickable elements on the notification

onClick callback function

If set and the internal notification bar shows hyperlinks then this callback is called when any of the links are clicked.

NotificationBar actions

A helper component NotificationBar.Action, that can be used for providing clickable action to notification definition.

interface NotificationBarActionProps {
    label: React.ReactText; // Can be simple text string or a template string
    onClick: NotificationBarActionCallback;
    icon?: string;
}


Browser notifications handler

if you want to display a browser notification, you shall use options key with a browser tag in it. Here is the exhaustive list of properties that forms the browser object:

BrowserNotificationOptions {
    title?: string;
    body?: string;
    onClick?: (notification: Notification, event: Event) => void;
    onClose?: (notification: Notification, event: Event) => void;
    onShow?: (notification: Notification, event: Event) => void;
    onError?: (notification: Notification, event: Event) => void;
    options?: NotificationOptions;
}

If no browser key is passed to options, Flex will not show any browser notifications.

Default standard notifications

NotificationId Notification type Description Default text of the notification UI template code
PendingReservationsOnLogout error A logout is forbidden while a worker has pending reservations You cannot logout while you have a pending task/reservation

PendingReservationsOnLogoutNotification

PendingReservationsOnActivityStateChange error Actitivity state cannot be changed while a worker has pending reservations You cannot update your activity while you have a pending task/reservation

PendingReservationsOnActivityStateChangeNotification

TransferFailed

error Task transfer failed due to recipient worker being unavailable Agent unavailable

TransferFailedNotification

BrowserVoiceDisabled

error Voice task accept failed due to Voice SDK being disabled Call cannot be accepted. Twilio Voice SDK has been disabled.

BrowserVoiceDisabledNotification

MicTaken

error Accessing the microphone has failed Unable to access microphone, please check browser settings.

MicNotAvailableNotification

CannotChangeOtherWorkerActivity

error Changing a worker's activity by the supervisor has failed due to the worker having pending reservations You cannot change an agent’s activity while they have a pending task/reservation.

CannotChangeOtherWorkerActivity

MonitoringFailed error Initiating call monitoring has failed Monitoring attempt has failed

MonitoringFailedNotification

MessageSizeExceeded error Sending chat message has failed due to an exceeded character limit The entered character number exceeds the limit - {{currentCharCount}}/{{maxCharCount}}

MessageSizeExceeded

ChatOrchestrationAddToChatChannelFailed error The worker could not be added to the chat channel after accepting chat based task Failed to add worker to the chat channel.

ChatOrchestrationAddToChatChannelFailed

ChatOrchestrationDeactivateChatChannelFailed error Chat channel could not be deactivated during wrapping up of chat based task Failed to deactivate the chat channel.

ChatOrchestrationDeactivateChatChannelFailed

ChatOrchestrationLeaveChatChannelFailed error Could not remove worker from chat channel during wrapping up of chat based task Failed to remove worker from the chat channel.

ChatOrchestrationLeaveChatChannelFailed

IncomingTask info Notification for incoming task, with most properties dependent on task channel in question Content depends on the type of task

Various templates depending on type of task

RequestBrowserNotificationPermissions

warning

Notification for asking for browser notification rights

We need your permission to <a href='#'>enable browser notifications</a>

RequestBrowserNotificationPermissions

NewChatMessage only browser

Notification shown when new chat message is received

Content depends on the type of task

NewChatMessageNotificationTitle

NewChatMessageNotificationBody

Working with Notifications

Register a custom notification with Browser notification handler

Flex.Notifications.registerNotification({
    id: "customNotification",
    closeButton: true,
    content: "Custom Notification",
    timeout: 0,
    type: NotificationType.warning,
    actions: [
        <NotificationBar.Action
            onClick={(_, notification) => {
                Flex.Notifications.dismissNotification(notification);
            }}
            label="Hello"
            icon="Bell"
        />
    ],
    options: {
      browser: {
          title: "Custom Notification",
          body: "Hello World!"
      }
  }
});

Override standard notifications for a specific task type using Task Channel Definitions API

Use custom notification for new reservation of a Call task

Flex.DefaultTaskChannels.Call.notifications.override.IncomingTask = () => {
  Flex.Notifications.showNotification("customNotification");
}

Change content of a standard notification for incoming call task

Flex.DefaultTaskChannels.Call.notifications.override.IncomingTask = (notification) => {
  notification.content: "Hello, world!";
};

Change content of a standard notification for new chat message

Flex.DefaultTaskChannels.Call.notifications.override.NewChatMessage = (notification) => {
  notification.content = "Hello, world!";
};

Turn off Standard Notifications

Do not show notificationBar notifications

MainContainer.defaultProps.showNotificationBar = false;

Disable notification by ID

Notifications.registeredNotifications.delete("notification_id");

Customize Standard Notifications

Change text of the notification

const notification = Notifications.registeredNotifications.get("notificationId");
notification.content = "Display some text";

Change text of the notification with template

manager.strings.myNotification = "Current time: {{time}}"
const notification = Notifications.registeredNotifications.get("notificationId");
notification.content = "myNotification";
Notifications.showNotification("notificationId", {time: Date.now()})

Read more about templates in Localization and UI templating

Render custom component in a notification

const notification = Notifications.registeredNotifications.get("notificationId");
notification.content = <MyAwesomePopup/>;

Change props of the notification

const notification = Notifications.registeredNotifications.get("PendingReservationsOnActivityStateChange");
notification.content = "Some text to display";
notification.backgroundColor = "blue";
notification.closeButton = false;

Register Custom Notifications

Option 1: string

Notifications.registerNotification({
id: "myNotificationId",
content: "Custom content", // string
type: NotificationType.error
});

Option 2: template

Notifications.registerNotification({
id: "myNotificationId",
content: "NotificationMessage", // template
type: NotificationType.error
});

Read more about templates in Localization and UI templating

Option 3: custom React component

interface CustomNotificationProps extends NotificationContentProps {
   customProp?: string;
   notificationContext?: any;
}

export class CustomNotificationElement extends React.Component<CustomNotificationProps, undefined> {
   render() {
       const { customProp, notificationContext } = this.props;
       return(
           <div>
               {notificationContext.message}
               <div />
               {customProp}
           </div>
       );
   }
}


Notifications.registerNotification({
    id: "myNotificationId",
    content: <CustomNotificationElement customProp="custom prop" />,
    type: NotificationType.error
    } 
);

Dispatch Custom Notifications

Option 1: string

Notifications.showNotification("myNotificationId", null);

Option 2 & 3: template & custom React component

Notifications.showNotification("myNotificationId", { message: "custom context" } );
Rate this page:

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.