0.5.0 • Published 6 months ago

@getchat-dev/web-button v0.5.0

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

Terms

GetChat is an out-of-the-box chat/messenger for your web services with closed source code. GetChat is available either as a cloud-based SaaS solution or as on-premises software for local installation.

Overview

Web-button is a compact JS library that allows you to integrate GetChat as a single button on your website. When this button is clicked, a small window with GetChat opens. This library is designed exclusively for browser usage and does not support Node.js, as it uses primitives available only in the browser environment.

Installation

npm install @getchat-dev/web-button

You can also use the legacy way and include the library on the page as follows:

(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0]
    if (d.getElementById(id)) return
    js = d.createElement(s)
    js.id = id
    js.src = 'https://getchat-dev.github.io/web-button/browser.js'
    fjs.parentNode.insertBefore(js, fjs)
}(document, 'script', 'getchat-jssdk'))

Getting started

The main purpose of this library is to add a button to the page that, when clicked, opens or closes the GetChat window. The main parameter, uri, is a specially generated link to the GetChat service, which loads the messenger in an iframe. For security reasons, this link is generated exclusively on the backend. In the code example below, it is assumed that the link generated by the backend is somehow assigned to the variable GETCHAT_URL_GENERATED_ON_BACKEND during page generation.

Adding the Button to the Page

Module way

import { GetChat } from '@getchat-dev/web-button'

const messenger: Chat = createButton({
    uri: GETCHAT_URL_GENRATED_ON_BACKEND,
    showUnread: 'chats',
    autoload: true,
    autoopen: false,
    autoopenDelay: false,
    buttonStyle: {
        position: 'fixed',
        bottom: '30px',
        right: '30px',
        display: 'inline-block',
        verticalAlign: 'middle',
        marginLeft: '22px'
    },
    chatStyle: {
        position: 'fixed',
        zIndex: '1000',
        bottom: '30px',
        right: '30px'
    }
}: CreateButtonOptions)

Script tag way

window.getchatonloaded = async function (SDK) {

    const messenger: Chat = SDK.createButton({
        uri: GETCHAT_URL_GENRATED_ON_BACKEND,
        showUnread: 'chats',
        autoload: true,
        autoopen: false,
        autoopenDelay: false,
        buttonStyle: {
            position: 'fixed',
            bottom: '30px',
            right: '30px',
            display: 'inline-block',
            verticalAlign: 'middle',
            marginLeft: '22px'
        },
        chatStyle: {
            position: 'fixed',
            zIndex: '1000',
            bottom: '30px',
            right: '30px'
        }
    }: CreateButtonOptions)

If using this method, you can get an instance of the Chat class as follows:

const messenger: Chat = document.querySelector('getchat-button').getChatInstance();

In the Interfaces section, you will find all the available parameters that can be passed to the createButton function.

How to Know When the Chat is Loaded

The Internet: An Unprecedented and Unparalleled Platform

Any loading process is asynchronous, and GetChat is no exception. The createButton method returns an instance of the Chat class, which provides the whenReady method. This method returns a promise that resolves when the chat is loaded and ready for use.

const messenger: Chat = SDK.createButton({
    uri: GETCHAT_URL_GENRATED_ON_BACKEND,
});

messenger.whenReady().then(async function () {
    console.log('Chat is ready');
});

How to Change the Button Style

Currently, the library supports changing the following seven parameters:

  • bgcolor – background color of the button
  • bdradius – border radius of the button
  • bdwidth – border width of the button
  • bdcolor – border color of the button
  • color – text and icon color of the button
  • badgebg – background color of the badge on the button
  • badgecolor – text color of the badge on the button

Declarative Button Style Declaration

When creating the button, you can pass style parameters in the options object.

const messenger: Chat = SDK.createButton({
    uri: GETCHAT_URL_GENRATED_ON_BACKEND,
    bdcolor: 'white',
    color: 'black',
    bdradius: '8px',
    bdwidth: '1px',
}: CreateButtonOptions)

Imperative Button Style Change

Here's an example of how to change the button style using the standard browser API through Element.setAttribute:

messenger.whenReady().then(async function () {
    // get button node
    const button = chat.getButton();
    if (button) {
        button.setAttribute('data-bgcolor', 'white');
        button.setAttribute('data-color', 'black');
        button.setAttribute('data-bdradius', '8px');
        button.setAttribute('data-bdwidth', '1px');
    }
});

How to Set a Custom Icon

Users can customize the button icon by passing either a URL or an SVG string to the setCustomIcon method.

Example Usage

Using an Icon URL:

const button: GetChatButton = messenger.getButton();
if (button) {
    button.setCustomIcon('https://example.com/my-custom-icon.png');
}

Using an SVG String:

const button: GetChatButton = messenger.getButton();
if (button) {
    button.setCustomIcon(`
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <circle cx="12" cy="12" r="10" stroke="black" stroke-width="2" fill="white"/>
            <path d="M8 12L12 16L16 12" stroke="black" stroke-width="2"/>
        </svg>
    `);
}

Important Notes

  • Set the icon as soon as possible: Avoid waiting for whenReady(), as this method waits for the chat iframe to fully load. However, setting the button icon does not depend on the iframe and should be done immediately after retrieving the button instance.
  • Icon format flexibility: The method supports both image URLs and inline SVG, allowing for easy customization.

How to Work with Push Notifications

If you want to enable push notifications, you need to request permission from the user. The library provides a method called initWebPushNotification that initializes the web push notification system and manages notification permissions.

Example: Calling the initWebPushNotification Method

You must call this method strictly after the chat is loaded and ready. The method returns an object with two properties: status and token.

  • The status property can have one of the following values:
    • "granted": The user has allowed notifications.
    • "denied": The user has blocked notifications.
    • "default": The user has not yet made a decision.
    • "unsupported": The browser does not support web push notifications.
  • The token property contains the FCM token if the status is "granted"; otherwise, it is null.

Using the status property, you can determine the current notification permission state to display an appropriate message to the user or update the notification toggler in your web application's settings.

await chat.whenReady();
const { status, token } = await chat.initWebPushNotification();

if (status === "granted" && token) {
    console.log("You have granted permission to receive notifications. FCM Token:", token);
}
else if(status === "denied") {
    console.log("You have denied permission to receive notifications.");
}
else if(status === "default") {
    console.log("You have not yet made a decision on whether to receive notifications.");
}
else if(status === "unsupported") {
    console.log("Your browser does not support web push notifications.");
}

Example: Requesting Notification Permission

await chat.whenReady();
// This must be called after the chat is fully initialized.
const { status, token } = await chat.initWebPushNotification();

// The browser allows requesting notification permission only if the status is "default".
// Otherwise, the user can change permissions only in the browser settings.
if (status === "default") {
    const activatePushButton = document.querySelector<HTMLButtonElement>('button[data-action="activate-push"]');
    if (activatePushButton) {
        activatePushButton.addEventListener("click", async (e: MouseEvent) => {
            e.preventDefault();

            try {
                const result: NotificationPermissionResult = await chat.requestNotificationPermission(e);
                console.log("Notification permission status:", result.status);
                if (result.token) {
                    console.log("FCM Token:", result.token);
                }
            }
            catch (error) {
                console.error("Failed to request notification permission:", error);
            }
        });
    }
}

Example: Disable Push Notifications

await chat.whenReady();
// This must be called after the chat is fully initialized.
const { status, token } = await chat.initWebPushNotification();

if (status === "granted" && token) {
    const button = document.querySelector<HTMLButtonElement>('button[data-action="disable-webpush"]');
    if (button) {
        button.addEventListener("click", async (e: MouseEvent) => {
            e.preventDefault();

            try {
                const status: Boolean = await chat.disableNotifications();
                if (status) {
                    console.log("FCM Token deleted successfully");
                }
            }
            catch (error) {
                console.error("Failed to disable notifications:", error);
            }
        });
    }
}

Handling Chat Events

To handle chat events, you can use the addEventListener method. For example, to handle the event of a new message, you can use the following code. It opens the chat upon receiving a new message and logs "New message received" to the console.

const messenger: Chat = SDK.createButton({
    uri: GETCHAT_URL_GENRATED_ON_BACKEND
});

messenger.addEventListener('getchat.chat.message.new', function () {
    messenger.open();
    console.log('New message received');
});

How to Know When the Chat Window is Opened or Closed

To determine whether the chat is currently open, you can use the isOpened method. This method returns true if the chat window is open and false otherwise.

Example Usage

if (messenger.isOpened()) {
    console.log('Chat is open');
} else {
    console.log('Chat is closed');
}

How to Check the Library Version at Runtime

To determine which version of the GetChat Web Button library is currently loaded, you can access the version property on the global window.GetChat object.

Example Usage:

console.log('GetChat Web Button version:', window.GetChat?.version);

Notes:

This property is available only after the library is fully loaded. If window.GetChat is undefined, it means the script has not yet been initialized.

Interfaces

CreateButtonOptions

Note: Options marked with * are required.

OptionTypeDescriptionDefault
uri*stringThe URI for the chat service.undefined
insertButtonTo*HTMLElement \| (() => HTMLElement) \| nullThe HTML element to insert the button into.undefined
classNamestringThe class name to apply to the button.undefined
showUnreadboolean \| 'messages' \| 'chats'Whether to show unread messages count.undefined
autoloadbooleanWhether to autoload the chat.false
autoopenbooleanWhether to open the chat widget automatically.false
autoopenDelaynumberDelay in milliseconds before auto open.5000
closeOnEscapebooleanWhether to close the chat on escape press.true
mobileModeMaxWidthnumberThe maximum width of the mobile mode.460
bgcolorstringBackground color of the button.undefined
bdradiusstringBorder radius of the button.undefined
bdwidthstringBorder width of the button.undefined
bdcolorstringBorder color of the button.undefined
badgebgstringBackground color of badge on the button.undefined
badgecolorstringColor of badge on the button.undefined
colorstringText color of the button.undefined
buttonStylePartial<CSSStyleDeclaration>Custom styles to apply to the button.undefined
chatClassNamestringClass name to apply to the chat window.undefined
chatParentHTMLElement \| nullThe parent HTML element of the chat window.undefined
chatStylePartial<CSSStyleDeclaration>Custom styles to apply to the chat window.undefined
chatNodeHTMLElement \| nullThe HTML element representing the chat node.undefined
nodeHTMLElement \| nullThe HTML element representing the node.undefined

ChatOptions Interface

PropertyTypeDefaultDescription
idstringN/AA unique identifier for the chat instance.
urlstringN/AThe URL of the chat service.
buttonHTMLElement \| nullN/AOptional HTML element for the chat trigger button.
autoloadbooleanfalseWhether to load the chat automatically on page load.
autoopenbooleanfalseWhether to start the chat automatically after loading.
autoopenDelaynumberN/ADelay in milliseconds before automatically opening the chat.
closeOnEscapebooleantrueWhether to close the chat on escape press.
onBeforeEmbedChat() => voidN/ACallback before the chat is embedded on the page.
onChatLoaded() => voidN/ACallback when the chat is fully loaded.
onBeforeOpen() => voidN/ACallback before the chat is opened.
onAfterOpenChat() => voidN/ACallback after the chat is opened.
onBeforeClose() => voidN/ACallback before the chat is closed.
onAfterCloseChat() => voidN/ACallback after the chat is closed.

Chat Class

MethodParametersReturnsDescription
constructoroptions: ChatOptionsN/AInitializes a new chat instance with the provided options.
whenReadyN/APromise<void>Resolves when the messenger is loaded and ready for interaction.
loadshowLoader?: booleanPromise<void>Loads the chat interface, optionally showing a loader.
isLoadedN/AbooleanReturns true if the chat iframe is fully loaded.
isOpenedN/AbooleanReturns true if the chat window is currently open.
toggleN/APromise<void>Toggles the visibility of the chat interface.
openN/APromise<void>Opens the chat interface.
closeN/APromise<void>Closes the chat interface.
addEventListenerevent: string, listener: () => voidN/ARegisters an event listener for specified chat events.
getButtonN/AHTMLElement \| nullReturns the chat trigger button element, if any.
getChatNodeN/AHTMLElement \| nullRetrieves the chat container element.
getChatIframeNodeN/AHTMLElement \| nullRetrieves the chat's iframe element, if using an iframe.
rpcmethod: string, params: any[], timeout?: numberPromise<any>Performs a remote procedure call to the chat service.
initWebPushNotificationsN/APromise<{ status: "granted" \| "denied" \| "default" \| "unsupported", token: string \| null }>Initializes web push notifications, retrieves FCM configuration, and manages notification permissions.
requestNotificationPermissionevent?: MouseEventPromise<NotificationPermissionResult>Requests notification permission from the user.
disableNotificationsN/APromise<boolean>Disables web push notifications.

GetChatButton Class

The GetChatButton class represents the custom chat button element and provides various methods for managing its state, icon, styles, and chat instance.

MethodParametersReturnsDescription
constructorN/AN/AInitializes a new instance of GetChatButton.
setChatInstancechatInstance: ChatvoidAssociates a Chat instance with this button.
getChatInstanceN/AChatRetrieves the associated Chat instance.
setStatestate: 'loaded' | 'loading'voidSets the state of the button (e.g., "loading", "loaded").
setBadgevalue: numbervoidSets the badge count on the button.
setCustomIconicon: string, catchError: booleanbooleanSets a custom icon, either as an image URL or an SVG string.
setStylesstyles: objectvoidApplies custom styles to the button.
renderN/AvoidRe-renders the button element.

Custom Element Registration

The GetChatButton class is registered as a custom HTML element and can be used in the DOM as <getchat-button>. It is also available in the global HTMLElementTagNameMap:

declare global {
    interface HTMLElementTagNameMap {
        'getchat-button': GetChatButton;
    }
}
0.3.0

8 months ago

0.2.0

8 months ago

0.5.0

6 months ago

0.1.4

9 months ago

0.4.0

8 months ago

0.3.1

8 months ago

0.1.5

9 months ago

0.1.2

1 year ago

0.1.1

1 year ago