Platform
Use cases
Pricing
Ressources
DocumentationAPI 
Contact
Login
Schedule a demo
EN
FR
How to manage a chatbot using React

partager

How to manage a chatbot using React

Adding the Prisme.ai webchat in your single page application writen in React is easy like you would do on a static website. But you will have access to a lot more tools to interact with the dialog. There is two ways to implement the webchat.

Parution le 

July 1, 2021

, par 

Hadrien Lanneau

As a Chat Plugin

The simplest way  to display the webchat as a Chat Plugin. The chat will be
displayed in the corner corresponding to your settings and dialog will open
if you click it. But maybe you don't want the chat to be displayed everywhere
and you would interact with it by opening it automatically or send it events
which will start a conversation related to the current page. With this small
code extract, you will be able to do that :


let prismeaiScriptPromise;
const loadPrismaiScript = () => {
  if (!prismeScriptPromise) {
    prismeScriptPromise = new Promise((resolve, reject) => {
      const s = document.createElement("script");
      s.src = "//cdn.prisme.ai/wegobot_inject.js";
      s.onload = () => resolve();
      s.onerror = () => reject();
      document.body.appendChild(s);
    });
  }
  return prismeScriptPromise;
};

This single function will load once the Prisme.ai script and add to your global
environnement the `injectWegobot` function that you will be able to call when
you want :


await loadScript();
window.injectWegobot({
  botId: botId,
  fullscreen: false,
  apiCredentials: {
    parse: {
      APP_ID: "lrzrR2WoKff6oXTyZaQUUHY2KPkf4dkxizs8oAm4",
      SESSION_TOKEN_KEY: "SESSION_GOGOWEGO_TOKEN_KEY",
      API_BASE_URL: "https://api.prisme.ai/parse/1"
    }
  }
});

In bonus, you can access the Prisme.ai public API set to the global environnement:
`window.prismeai`.

So, if we resume that in a PrismeAi React component:


let prismeaiScriptPromise;
const loadPrismaiScript = () => {
  if (!prismeScriptPromise) {
    prismeScriptPromise = new Promise((resolve, reject) => {
      const s = document.createElement("script");
      s.src = "//cdn.prisme.ai/wegobot_inject.js";
      s.onload = () => resolve();
      s.onerror = () => reject();
      document.body.appendChild(s);
    });
  }
  return prismeScriptPromise;
};

export const PrismeAi = ({ botId }) => {
  const prismeapi = React.useRef();
  const initWebchat = React.useCallback(async () => {
    await loadScript();
    window.injectWegobot({
      botId,
      fullscreen: false,
      apiCredentials: {
        parse: {
          APP_ID: "lrzrR2WoKff6oXTyZaQUUHY2KPkf4dkxizs8oAm4",
          SESSION_TOKEN_KEY: "SESSION_GOGOWEGO_TOKEN_KEY",
          API_BASE_URL: "https://api.prisme.ai/parse/1"
        }
      }
    });
    prismeapi.current = window.prismeai;
  }, [botId]);

  React.useEffect(() => {
    initWebchat()

    return () => {
      prismeapi.current.destroy();
    }
  }, [initWebchat]);

  return null;
}

<PrismeAi botId="42" />

In an iframe

You can display the webchat in a view of the size of your choice and where you want by using an iframe. The implementation will be a little more complex. You will have to add an iframe in your DOM, then you will set its content by using the `src` attribute:


iframe.src = "data:text/html;charset=utf-8," +
  encodeURI(`
  <body>
    <script type="text/javascript" src="https://cdn.prisme.ai/wegobot_inject.js" charset="UTF-8"></script>
    <script type="text/javascript">
    window.injectWegobot({
      "botId": "${botId}",
      "fullscreen": 1,
      "apiCredentials": {
        "parse": {
          "APP_ID": "lrzrR2WoKff6oXTyZaQUUHY2KPkf4dkxizs8oAm4",
          "SESSION_TOKEN_KEY": "SESSION_GOGOWEGO_TOKEN_KEY",
          "API_BASE_URL": "https://api.prisme.ai/parse/1"
        }
      }
    });
    </script>
  </body>
`);

The webchat will be loaded in fullscreen inside your iframe. In a React component it should be implemented like:


export const PrismeAi = ({ botId }) => {
  const ref = React.useRef();
  React.useEffect(() => {
    ref.current.src = "data:text/html;charset=utf-8," +
      encodeURI(`
      <body>
        <script type="text/javascript" src="https://cdn.prisme.ai/wegobot_inject.js" charset="UTF-8"></script>
        <script type="text/javascript">
        window.injectWegobot({
          "botId": "${botId}",
          "fullscreen": 1,
          "apiCredentials": {
            "parse": {
              "APP_ID": "lrzrR2WoKff6oXTyZaQUUHY2KPkf4dkxizs8oAm4",
              "SESSION_TOKEN_KEY": "SESSION_GOGOWEGO_TOKEN_KEY",
              "API_BASE_URL": "https://api.prisme.ai/parse/1"
            }
          }
        });
        window.addEventListener('message', (e) => {
          try {
            const data = JSON.parse(e.data)
            window.prismeai.action(data)
          } catch (e) {}
        })
        </script>
      </body>
		`);
  }, []);
  
  const sendAction = ({ type, value }) =>
  	ref.current.contentWindow.postMessage(JSON.stringigy({ type, value }), '*')

  return <iframe ref={ref} />
}

In this way, you won't have access to `window.prismeai` api but you will be able to communicate with the dialog by using postMessage.

Communicate with the Dialog

The dialog expose a public API wich will help you to give it commands. There is two ways to access it:

  • from calling the injectWegobot function. A global `window.prismeai.action()` function will be set. This function takes an object with `type` and `value` : `window.prismeai.action({ type: 'text', value: 'Hello' })`
  • from posting messages to the iframe : iframe.contentWindow(JSON.stringify({ type: 'text', value: 'Hello' }), '*')

API

  • type: text. Value should be a string. Send text to the chatbot like if the user would have.
  • type: event. Value should be a string. Send an event to the chatbox like if the user would have click a button.
  • type: toggle. Value can be true or false. Open or close the dialogbox.
  • type: resetConversation. No value. Reset the conversation.
  • type: navigate. Value can be "chatbot" or "notifications". Change current view in the dialog box.
  • type: setParameters. Value should be an object with any valid configuration parameter.
  • type: changeLanguage. Value should be a country code in two characters as string. Change the dialog wordings translations.
  • type: togglePanel. Value can be true or false. Open or close the panel.
  • type: pushPanelItems. Value should be an array of objects with title (string), text (string) and isActive (boolean) values. Will add some items in the opened panel.

More on documentation

In action

PlatformUse casesPricing
BlogDocumentationRecruitment
LoginBlagnac, France
CGULegal TermsPrivacy Policy

All rights reserved Prisme.ai - 2021 - Gogowego SAS - Made In Francecréation de site internet polish_ studiocréation de site internet polish_ studio