> For the complete documentation index, see [llms.txt](https://docs.chatlayer.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.chatlayer.ai/chatlayer-documentation-pt-br/channels/all-channels/web/webwidget/live-example-web-widget.md).

# Widget da web com 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 migrar para o** [**novo widget da web, Web V2**](/chatlayer-documentation-pt-br/channels/all-channels/web/web-v2.md)**.** Isso significa que o Web V1 será removido da nossa base de código. Saiba tudo sobre [a migração da V1 para a V2](/chatlayer-documentation-pt-br/channels/all-channels/web/web-v2/from-web-v1-to-v2.md).
{% endhint %}

Criamos um exemplo de como você pode inicializar e destruir o widget de chat da Chatlayer.ai por meio do seu próprio código JavaScript.

```markup
<html>
  <head>
    <title>Exemplo de eventos do Chatlayer</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 mostra a destruição de um webwidget da Chatlayer
       * ao acionar 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 da Chatlayer ...");
        chatlayerInstance = chatlayer({ lang: "en" });
        // Os tipos de evento são "event", "open" e "close"

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

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

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

      const destroyChatlayer = () => {
        if (!chatlayerInstance) return;
        console.log("Destruindo o widget da 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 a Chatlayer primeiro!");
          return;
        }
        chatlayerInstance.open();
      };

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

    <!-- Observe a ausência da prop onload no seguinte script tag. -->
    <!-- Para inicializar automaticamente o webwidget, você adicionaria a prop: -->
    <!-- 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" %}
Ver 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 disparar um evento de destruição do chat widget.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.chatlayer.ai/chatlayer-documentation-pt-br/channels/all-channels/web/webwidget/live-example-web-widget.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
