Přeskočit na hlavní obsah

Help Widget Developer Guide

Table of Contents

  1. Introduction
  2. Installation & Initialization
  3. Widget Configuration
  4. Widget Control API
  5. Display Mode Examples
  6. Advanced Topics
  7. Best Practices

Introduction

MessageOk Widget is a customizable widget that can be embedded into any website. This guide covers the JavaScript API for controlling and configuring the widget on your website.

Installation & Initialization

First, you have to load our javascript script for communication with widget. The script is available on:

<script src="https://cdn.msgok.net/client/widget/widget-v21-beta.js"></script>

Initialization is handled via a global queue, which ensures that configurations are ready before the script executes.

Step 1: Define the Initialization Queue Before the script tag, create an array named window.msgokInitQueue and push a configuration object for each widget instance you want to create.

Step 2: Load the Widget Script Include the widget-v21-beta.js script with the defer attribute.

Step 3: Listen for the Ready Event To interact with the widget's API, listen for the helpWidgetReady event on the window object. This event fires after all widgets in the queue have been initialized.

<!-- 1. Initialize the queue -->
<script>
window.msgokInitQueue = window.msgokInitQueue || [];
window.msgokInitQueue.push({
instanceId: 'msgokwidget',
options: {
displayMode: 'popup',
template: '[your-widget-id]',
primaryColor: '#f97316',
buttonText: 'Need help?',
}
});
</script>

<!-- 2. Load the widget script -->
<script src="https://cdn.msgok.net/client/widget/widget-v21-beta.js" defer></script>

<!-- 3. Use the API after the widget is ready (optional) -->
<script>
window.addEventListener('helpWidgetReady', function() {
if (window.msgokwidget) {
console.log('Widget `msgokwidget` is ready!');
// You can now use the API, e.g., window.msgokwidget.open();
}
});
</script>

Widget Configuration

The widget's behavior and appearance are controlled by the options object passed into the initialization queue.

Configuration Options

OptionTypeDefaultDescription
displayModestring'popup''popup', 'modal', or 'inline'.
templatestringyou can find this value in your accountID of your profile.
targetstringnullCSS selector for the container where an 'inline' widget should be rendered. Required for inline mode.
buttonTypestring'icon-only''icon-only', 'text-only', 'icon-and-text'.
buttonTextstring'Need help?'Text for the widget button.
buttonDescriptionstring''Sub-text that appears below the main button text.
buttonTextClosestring'Close'Text for the widget button when the widget is open.
iconPositionstring'before'For 'icon-and-text' buttons, positions the icon 'before' or 'after' the text.
buttonIconSvgstringnullCustom SVG string for the "open" icon.
buttonCloseIconSvgstringnullCustom SVG string for the "close" icon.
primaryColorstring'#f97316'Main color for the button and other primary elements.
hoverColorstringcomputed from primaryColorHover color for the button. Optional.
showMobilebooleantrueWhether to show the widget on screens <= 768px wide.
hideByDefaultbooleanfalseIf true, the widget is hidden on load and must be shown programmatically via .show() or .open().
enablePulsebooleantrueIf true, the button will have a pulsing animation when closed.
blacklistUrlstring[][]An array of URL path substrings. The widget will be hidden if the current path matches any of them.
widthDefaultnumber380Default width in pixels for popup/inline modes.
widthExpandnumber450Maximum width the popup can expand to via messages from the iframe.
maxHeightnumber600Maximum height in pixels for the popup/inline container.
widthBannernumber300Default width for banners triggered by this instance.
variablesobject{}Key-value pairs passed to the iframe session. Useful for be able to read user data inside flows.
menuItemsarray[]An array of menu item objects to display in the widget's main view. See below for details.
bannersarray[]An array of static banner configuration objects.
widgetConfigobject{}A configuration object passed directly to the widget for more customization. See next table

Additional Configuration Options

OptionTypeDefaultDescription
recipientstringyou can find this value in your accountID of your account.
titlestring''The main title displayed in the widget header or home view.
subtitlestring''A subtitle or secondary text shown below the title.
primaryColorstring'#f97316'Main color for the widget (overrides the default if set here).
showTitleOnHomebooleantrueWhether to display the title on the home view of the widget or show hero section.
availableLanguagesstring[]['en']Array of supported language codes for the widget interface.
translationsobject{}Custom translations for interface text, keyed by language code.
customCssstring''Custom CSS string to further style the widget.
heroContentobject{}If you want to use special hero section, you can .

You can define the main navigation of the widget by passing an array of menuItems. This is useful for setting up the main menu of widget from your side (or create it programmatically).

// Example of menuItems in widget options
options: {
// ... other options
menuItems: [
{
"id": "faq", //not mandatory
"title": "FAQ",
"description": "Find answers to common questions",
"icon": "IconHelpCircle",
"type": "link",
"linkContentId": "faq-section" //content with this ID must already exist
}
]
}

Structure of menuItems

TypeDescriptionRelevant Properties
linkNavigates to an internal content page (a LinkContent object).id, title, icon, linkContentId (ID of the content to display).
searchNavigates to the search view. Can optionally pre-fill the search input.id, title, icon, searchValue (optional, a string to pre-fill the search with).
urlOpens an external URL in a new browser tab.id, title, icon, link (the URL to open), external (should be true).
formStarts a multi-step form or submits a value in an ongoing form.id, title, icon, target (the payload or ID for the form action).
external-chatTriggers the loading of a third-party chat widget (e.g., Smartsupp, Tawk.to).id, title, icon, target (a JSON string with the service configuration, e.g., {"serviceId":"smartsupp","key":"YOUR_KEY"}).
ask-boxDisplays an input field for submitting a question to a backend AI service.id, title, icon, description, askSupport (optional, a payload/ID to use for a "contact support" fallback button in the AI response view).
search-boxDisplays a dedicated search input field in the home view.id, title, icon, description.
text-boxDisplays a simple block of text.id, title, icon, description, textBoxContent (an object with a content property).
text-headlineA non-interactive item used to display a heading to group other menu items.title.

Widget Control API

The widget instance exposes methods through the Control API. These methods allow you to control the widget programmatically after it has been initialized.

Information Methods

getInstanceId()

Returns the instance ID of the widget. myWidget.getInstanceId(); // 'main-widget'

isOpen()

Checks if the widget is currently open (popup/modal modes only). myWidget.isOpen(); // true or false

getButtonElement()

Returns the button DOM element (null for inline mode).

getContainerElement()

Returns the container DOM element.

getFrameElement()

Returns the iframe DOM element.

getConfig()

Returns a copy of the widget's current configuration. const config = myWidget.getConfig();

Visibility Control Methods

open()

Opens the widget (popup/modal only).

close()

Closes the widget (popup/modal only).

toggle()

Toggles the open/close state (popup/modal only).

show()

Makes the widget button visible if it was hidden by hide() or hideByDefault.

hide()

Hides the widget button and container completely.

openToContent(contentId, forceExpand)

Opens the widget and navigates to specific content.

  • contentId (string): The ID of the content to display.
  • forceExpand (boolean, optional): If true, forces the popup to its widthExpand size.

openToSearch(searchValue)

Opens the widget and performs a search.

  • searchValue (string, optional): The search term.

openToForm(formId, variables, standalone)

Opens the widget and navigates to a specific form.

  • formId (string): The ID of the form to display.
  • variables (object, optional): Pre-fills form fields with matching keys.
  • standalone (boolean, optional): If true, hides iframe navigation, showing only the form.

Configuration Update Methods

changeButtonType(type)

Changes the button type. type can be 'icon-only', 'text-only', or 'icon-and-text'.

changeButtonText(text, closeText)

Changes the button text.

changeButtonDescription(description)

Changes the button's sub-text.

changeIconPosition(position)

Changes icon position ('before' or 'after') for 'icon-and-text' buttons.

changeButtonIcons(helpIconSvg, closeIconSvg)

Sets custom SVG strings for the open and close icons.

toggleMobileVisibility(show)

Controls visibility on mobile devices (show is boolean).

updateBlacklist(blacklist)

Updates the URL paths where the widget should be hidden.

togglePulseEffect(enable)

Enables or disables the pulsing animation on the button.

updateBanners(banners)

Updates the static banners configuration and re-evaluates conditions.

updateMenuItems(menuItems)

Updates the menu items in the widget's main view.

setPrimaryColor(color)

Sets the primary color for the widget button.

setHoverColor(color)

Sets the hover color for the widget button.

setVariable(key, value)

Sets a variable for the widget session and sends it to the iframe.

Dynamic Banner Methods

addDynamicBanner(bannerConfig)

Adds or updates a dynamic banner. See the Dynamic Banners section for details.

Cleanup Methods

destroy() / remove()

Removes the widget instance, its DOM elements, and associated event listeners. remove() is an alias for destroy().

Display Mode Examples

The widget appears as a popup from the corner (default bottom-right).

<script>
window.msgokInitQueue.push({
instanceId: 'popup-example',
assignToWindowAs: 'popupWidget',
options: {
displayMode: 'popup',
template: '[your-widget-id]', // Use 'template'
primaryColor: '#f97316',
buttonType: 'icon-and-text',
buttonText: 'Need Help?',
}
});
</script>

The widget appears as a modal dialog centered on the screen.

<script>
window.msgokInitQueue.push({
instanceId: 'modal-example',
assignToWindowAs: 'modalWidget',
options: {
displayMode: 'modal',
template: '[your-widget-id]', // Use 'template'
buttonType: 'text-only',
buttonText: 'Help Center',
}
});
</script>

Inline Mode

The widget is embedded directly into a container element on the page.

<div id="help-widget-container" style="height: 500px; border: 1px solid #ccc;"></div>

<script>
window.msgokInitQueue.push({
instanceId: 'inline-example',
options: {
displayMode: 'inline',
template: '[your-widget-id]', // Use 'template'
target: '#help-widget-container', // Required for inline mode
variables: {
department: 'sales'
}
}
});
</script>

Advanced Topics

URL-Based Control

You can control the widget directly from the page URL using query parameters. This is useful for linking directly to help content from emails or other applications.

  • ?msgok=open: Opens the widget.
  • ?ref=content:{contentId}: Opens the widget to a specific content page.
  • ?ref=runId:abc:storno: A special-case example that opens a specific form.
  • You can also use a hash: #msgok=content:{contentId}.

Example URL: https://your-website.com/dashboard?msgok=content:getting-started

Create a modal widget that's hidden by default and opens to specific content when triggered.

<a href="#" id="open-faq">Frequently Asked Questions</a>
<a href="#" id="open-contact">Contact Support</a>

<script>
// Add widget to queue
window.msgokInitQueue = window.msgokInitQueue || [];
window.msgokInitQueue.push({
instanceId: 'hidden-modal-example',
assignToWindowAs: 'hiddenModalWidget',
options: {
displayMode: 'modal',
template: '[your-widget-id]',
hideByDefault: true, // Hide until explicitly shown
}
});

// Setup triggers after widget is ready
window.addEventListener('helpWidgetReady', function() {
const widget = window.hiddenModalWidget;
if (!widget) return;

document.getElementById('open-faq').addEventListener('click', (e) => {
e.preventDefault();
widget.openToContent('faq-section');
});

document.getElementById('open-contact').addEventListener('click', (e) => {
e.preventDefault();
widget.openToForm('contact-support');
});
});
</script>

Dynamic Banners

Dynamic banners can be triggered based on user behavior or page conditions.

Use cases

  • Once the order is completed, you can create a dynamic banner that actively notifies the user of the order status on their next visit.

Banners (both static and dynamic) support the following properties:

  • id, title, description, buttons (array of button objects).
  • expiresAt (ISO 8601 string): When the banner should no longer be shown.
  • showAt (ISO 8601 string): Delays showing the banner until the specified time.
  • force (boolean): If true, the banner will reappear on the next page load even if closed by the user, until it expires.
  • conditions:
    • timeOnPage (seconds): Time to wait before showing.
    • pageUrl (string): Substring or regex to match window.location.pathname.
    • pageLoads (number): Minimum number of page loads.
  • targetInstanceId: For dynamic banners, specifies which widget instance should handle button clicks (like 'link' or 'form'). Required for such actions.

addDynamicBanner(bannerConfig)

myWidget.addDynamicBanner({
id: 'promo-banner',
title: 'We are working on your order!',
description: 'Thank you for your order #123456789. Do you have any questions about it?',
expiresAt: '2024-12-31T23:59:59Z',
targetInstanceId: 'main-widget', // Required for actions below
buttons: [{ id: 'dyn-ok', text: 'See status', type: 'form', formId: '{"runId":"abc:orderstatus"}', variables: { 'obj': '123456789' } }],
conditions: {
pageUrl: '/contact'
}
});

State Management

The widget automatically saves its state to localStorage. This includes:

  • Open/Closed State: If a user leaves a page with a popup or modal widget open, it will automatically reopen when they navigate to a new page on the same site.
  • Last Content State: The widget also remembers the last viewed content and will restore it.

This behavior provides a seamless experience in Single Page Applications (SPAs) or during standard page navigation. State is automatically cleared when the user closes the widget or when .destroy() is called.

Localization

They also provide a way to localize the content of the widget.

  1. You can localize menu items and add them to the widget queue during initialization.

  2. The widget usually contains interface labels, such as a tooltip for the back button, error messages, and more. This text has already been localized into dozens of languages. Use the parameter "defaultLanguage" and set it to one of the supported languages: cs, sk, pl, or en.

  3. If you want to use a custom translation, use the parameter "translations," which should be an object where the key is the language code and the value is an object with the translation ID and text. Here are all the implemented translation IDs:

  ...
defaultLanguage: 'en',
translations: {
cs: {
"header.back": "Zpět",
"header.home": "Úvod",
"header.search": "Hledat",
"header.close": "Zavřít",
"form.close": "Zavřít",
"form.retry": "Zkusit znovu"
}
}
...

External Chat Integration

The widget can act as a bridge to load a third-party chat service (e.g., Smartsupp, Tawk.to).

Process:

  1. A user clicks on a button inside the widget, such as "Chat with an agent."
  2. The third-party chat script is then dynamically injected into the page.
  3. Once the third-party chat notifies the widget that the load is complete, the MessageOk Widget instance is destroyed and the third-party chat UI takes over. For inline widgets, the widget is not destroyed.

Best Practices

  1. Unique Instance IDs: Ensure each widget instance has a unique ID.
  2. Use the Init Queue: Always use window.msgokInitQueue for initialization.
  3. Widget Cleanup: Call myWidget.destroy() when removing widgets, especially in single-page applications, to clean up resources.
  4. Dynamic Banners: Use targetInstanceId for banners with actions and set appropriate expiration times to avoid overwhelming users.
  5. Performance: Limit the number of concurrent widget instances on a page.
  6. Blacklists: Use URL blacklists to hide widgets on sensitive or transactional pages like checkout or admin areas.