JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 6
  • Score
    100M100P100Q44791F
  • License MIT

Package Exports

  • @getchat-dev/web-button
  • @getchat-dev/web-button/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@getchat-dev/web-button) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

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.

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 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.

Option Type Description Default
uri* string The URI for the chat service. undefined
insertButtonTo* HTMLElement | (() => HTMLElement) | null The HTML element to insert the button into. undefined
className string The class name to apply to the button. undefined
showUnread boolean | 'messages' | 'chats' Whether to show unread messages count. undefined
autoload boolean Whether to autoload the chat. false
autoopen boolean Whether to open the chat widget automatically. false
autoopenDelay number Delay in milliseconds before auto open. 5000
closeOnEscape boolean Whether to close the chat on escape press. true
mobileModeMaxWidth number The maximum width of the mobile mode. 460
bgcolor string Background color of the button. undefined
bdradius string Border radius of the button. undefined
bdwidth string Border width of the button. undefined
bdcolor string Border color of the button. undefined
badgebg string Background color of badge on the button. undefined
badgecolor string Color of badge on the button. undefined
color string Text color of the button. undefined
buttonStyle Partial<CSSStyleDeclaration> Custom styles to apply to the button. undefined
chatClassName string Class name to apply to the chat window. undefined
chatParent HTMLElement | null The parent HTML element of the chat window. undefined
chatStyle Partial<CSSStyleDeclaration> Custom styles to apply to the chat window. undefined
chatNode HTMLElement | null The HTML element representing the chat node. undefined
node HTMLElement | null The HTML element representing the node. undefined

ChatOptions Interface

Property Type Default Description
id string N/A A unique identifier for the chat instance.
url string N/A The URL of the chat service.
button HTMLElement | null N/A Optional HTML element for the chat trigger button.
autoload boolean false Whether to load the chat automatically on page load.
autoopen boolean false Whether to start the chat automatically after loading.
autoopenDelay number N/A Delay in milliseconds before automatically opening the chat.
closeOnEscape boolean true Whether to close the chat on escape press.
onBeforeEmbedChat () => void N/A Callback before the chat is embedded on the page.
onChatLoaded () => void N/A Callback when the chat is fully loaded.
onBeforeOpen () => void N/A Callback before the chat is opened.
onAfterOpenChat () => void N/A Callback after the chat is opened.
onBeforeClose () => void N/A Callback before the chat is closed.
onAfterCloseChat () => void N/A Callback after the chat is closed.

Chat Class

Method Parameters Returns Description
constructor options: ChatOptions N/A Initializes a new chat instance with the provided options.
whenReady N/A Promise<void> Resolves when the messenger is loaded and ready for interaction.
load showLoader?: boolean Promise<void> Loads the chat interface, optionally showing a loader.
toggle N/A Promise<void> Toggles the visibility of the chat interface.
open N/A Promise<void> Opens the chat interface.
close N/A Promise<void> Closes the chat interface.
addEventListener event: string, listener: () => void N/A Registers an event listener for specified chat events.
getButton N/A HTMLElement | null Returns the chat trigger button element, if any.
getChatNode N/A HTMLElement | null Retrieves the chat container element.
getChatIframeNode N/A HTMLElement | null Retrieves the chat's iframe element, if using an iframe.
rpc method: string, params: any[], timeout?: number Promise<any> Performs a remote procedure call to the chat service.

GetChatButton Class

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

Method Parameters Returns Description
constructor N/A N/A Initializes a new instance of GetChatButton.
setChatInstance chatInstance: Chat void Associates a Chat instance with this button.
getChatInstance N/A Chat Retrieves the associated Chat instance.
setState `state: 'loaded' 'loading'` void
setBadge value: number void Sets the badge count on the button.
setCustomIcon icon: string, catchError: boolean boolean Sets a custom icon, either as an image URL or an SVG string.
setStyles styles: object void Applies custom styles to the button.
render N/A void Re-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;
    }
}