# Widget web de exemplo ao vivo

{% hint style="danger" %}
**A partir de 31 de outubro de 2024, todos os clientes da Chatlayer que usam o canal Web precisarão mudar para o** [**novo widget web, Web V2**](https://docs.chatlayer.ai/chatlayer-documentation-pt-br/channels/all-channels/web/web-v2)**.** Isso significa que o Web V1 será removido da nossa base de código. Saiba tudo sobre [migrar do V1 para o V2](https://docs.chatlayer.ai/chatlayer-documentation-pt-br/channels/all-channels/web/web-v2/from-web-v1-to-v2).
{% endhint %}

Criamos um exemplo de como você pode inicializar e destruir o widget de chat do Chatlayer.ai através do seu próprio código Javascript.

```markup
<html>
  <head>
    <title>Chatlayer Events Example</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <button onclick="initChatlayer()">Inicializar Chatlayer</button>
    <button onclick="destroyChatlayer()">Destruir Chatlayer</button>
    <br />
    <br />
    <button onclick="openChatlayer()">Abrir Widget do Chatlayer</button>
    <button onclick="closeChatlayer()">Fechar Widget do Chatlayer</button>

    <script>
      /**
       * Este exemplo demonstra a destruição de um webwidget do Chatlayer
       * acionando o plugin JSON builder no fluxo.
       *
       * A caixa de diálogo da ação JSON builder foi configurada da seguinte forma:
       * https://minio.dev.chatlayer.ai/public/JSONBuilder.png
       *
       */

      let chatlayerInstance = null;

      const initChatlayer = () => {
        if (chatlayerInstance) return;
        console.log("Inicializando o widget Chatlayer ...");
        chatlayerInstance = chatlayer({ lang: "en" });
        // Os tipos de evento são "event", "open" e "close"

        chatlayerInstance.on("open", event => {
          console.log('OPENED');
        });

        chatlayerInstance.on("close", event => {
          console.log('CLOSED')
        });

        chatlayerInstance.on("event", event => {
          // Observe o conteúdo do event aqui: a chave "action" com valor "destroy"
          // se origina diretamente da ação do JSON Builder configurada.
          const isChatlayerDestroyEvent = event.action === "destroy";
          if (isChatlayerDestroyEvent) {
            destroyChatlayer();
          }
        });
      };

      const destroyChatlayer = () => {
        if (!chatlayerInstance) return;
        console.log("Destruindo o widget Chatlayer ...");
        // Para destruir o widget, ele precisa ser aberto primeiro
        chatlayerInstance.open();
        chatlayerInstance.destroy();
        chatlayerInstance = null;
      };

      const openChatlayer = () => {
        if (!chatlayerInstance) {
          console.log("Por favor, inicialize o Chatlayer primeiro!");
          return;
        }
        chatlayerInstance.open();
      };

      const closeChatlayer = () => {
        if (!chatlayerInstance) {
          console.log("Por favor, inicialize o Chatlayer primeiro!");
          return;
        }
        chatlayerInstance.close();
      };
    </script>

    <!-- Observe a ausência da propriedade onload na tag de script a seguir. -->
    <!-- Para inicializar automaticamente o webwidget, você adicionaria a propriedade: -->
    <!-- onload="initChatlayer()" -->
    <script
      src="https://chatbox.staging.chatlayer.ai/sdk/5ecbcf1514c3dc4942f05f96"
      async
    ></script>
  </body>
</html>
```

Configuração do plugin JSON builder:

![](https://181262846-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LLTwFwbOqJj4dDhg8Ju%2F-M8BYZ0rFc274QsygIov%2F-M8BZt06OqDoM5_E2u71%2Fimage.png?alt=media\&token=179a1c12-f52c-470d-8fec-de0b4a666fa0)

{% hint style="info" %}
Veja uma versão ao vivo deste código [aqui](https://codesandbox.io/s/chatlayer-destroy-webwidget-s0lnj?file=/index.html).
{% endhint %}

Como você pode ver no exemplo acima, você pode inicializar o widget, abri-lo/fechá-lo, bem como destruí-lo a partir do seu próprio código. O exemplo mostra como usar o plugin JSON Builder para acionar um evento de destruição para o widget de chat.
