Live example web widget
We've created an example of how you can initialize and destroy the Chatlayer.ai chat widget through your own Javascript code.
1
<html>
2
<head>
3
<title>Chatlayer Events Example</title>
4
<meta charset="UTF-8" />
5
</head>
6
​
7
<body>
8
<button onclick="initChatlayer()">Initialize Chatlayer</button>
9
<button onclick="destroyChatlayer()">Destroy Chatlayer</button>
10
<br />
11
<br />
12
<button onclick="openChatlayer()">Open Chatlayer Widget</button>
13
<button onclick="closeChatlayer()">Close Chatlayer Widget</button>
14
​
15
<script>
16
/**
17
* This example showcases the destruction of a Chatlayer webwidget
18
* by triggering the JSON builder plugin in the flow.
19
*
20
* The JSON builder action dialog was set up as follows:
21
* https://minio.dev.chatlayer.ai/public/JSONBuilder.png
22
*
23
*/
24
​
25
let chatlayerInstance = null;
26
​
27
const initChatlayer = () => {
28
if (chatlayerInstance) return;
29
console.log("Initializing the Chatlayer widget ...");
30
chatlayerInstance = chatlayer({ lang: "en" });
31
// Event types are "event", "open" and "close"
32
​
33
chatlayerInstance.on("open", event => {
34
console.log('OPENED');
35
});
36
​
37
chatlayerInstance.on("close", event => {
38
console.log('CLOSED')
39
});
40
​
41
chatlayerInstance.on("event", event => {
42
// Note the content of event here: the "action" key with value "destroy"
43
// originates directly from the configured JSON Builder action.
44
const isChatlayerDestroyEvent = event.action === "destroy";
45
if (isChatlayerDestroyEvent) {
46
destroyChatlayer();
47
}
48
});
49
};
50
​
51
const destroyChatlayer = () => {
52
if (!chatlayerInstance) return;
53
console.log("Destroying the Chatlayer widget ...");
54
// To destroy the widget, it has to be opened first
55
chatlayerInstance.open();
56
chatlayerInstance.destroy();
57
chatlayerInstance = null;
58
};
59
​
60
const openChatlayer = () => {
61
if (!chatlayerInstance) {
62
console.log("Please initialize Chatlayer first!");
63
return;
64
}
65
chatlayerInstance.open();
66
};
67
​
68
const closeChatlayer = () => {
69
if (!chatlayerInstance) {
70
console.log("Please initialize Chatlayer first!");
71
return;
72
}
73
chatlayerInstance.close();
74
};
75
</script>
76
​
77
<!-- Note the absence of the onload prop on the following script tag. -->
78
<!-- To automatically initialize the webwidget, you would add the prop: -->
79
<!-- onload="initChatlayer()" -->
80
<script
81
src="https://chatbox.staging.chatlayer.ai/sdk/5ecbcf1514c3dc4942f05f96"
82
async
83
></script>
84
</body>
85
</html>
Copied!
JSON builder plugin configuration:
View a live version of this code here.
As you can see from the example above, you can initialize the widget, open/close it, as well as destroy it from your own code. The example shows you how to use the JSON Builder plugin to trigger a destroy event for the chat widget.
Last modified 3mo ago
Copy link