# Scripting

The MyLINK Connect widget script supports multiple functions you can use to interact with the chat from an external script or to alter chat rendering during execution.[ You can find here](https://www.xenioo.com/showcase/events-log/) an interactive example of the most widely used functions.

## Events

Events are fired as the user or the bot execute specific operations. Your script can implement these events by simply supplying your own function inside the initialization script. In the following example, the initialization script is attaching to the onChatShow event:

```markup
<script [...] src="https://res.xenioo.com/plugin/xenioo.js"></script>
<script>
    xenioowebchat.Start("<chatbotid>",{
        onChatShow : function(){
        	console.log( "Chat area is now visible." );
        }
    });
</script>
```

Below you can find the full list of the supported events:

| Event                      | Description                                                                                                                                                         | Parameters                                                                                            |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
| onInit                     | Fired as soon as chatbot initializations is started                                                                                                                 | None                                                                                                  |
| onReady                    | Fired when initialization ends and the chatbot is ready                                                                                                             | None                                                                                                  |
| onChatClose                | Happens every time the user closes the chat window                                                                                                                  | None                                                                                                  |
| onChatShow                 | Happens every time the user or a script opens the chat window                                                                                                       | None                                                                                                  |
| onChatHide                 | Happens every time the user or a script closes the chat window                                                                                                      | None                                                                                                  |
| onWidgetClick              | Fired as the user clicks on the chat widget on the bottom right                                                                                                     | calloutclicked = true if the user opened the chat by clicking on the callout bubble, false otherwise. |
| onDataConnection           | Fired whenever the chatbot is retrieving data from the MyLINK Connect servers                                                                                       | None                                                                                                  |
| onItemRender               | Fired every time a single item is rendered in the chat window                                                                                                       | obj = the instance of the chat part to be rendered                                                    |
| onElementRender            | Fired after the chat element to be rendered is ready to be added to the DOM                                                                                         | <p>element = DOM node instance</p><p>obj = the instance of the chat part to be rendered</p>           |
| onButtonClick              | Fired as a button is clicked in the chat window                                                                                                                     | say = The text of the button, command = the id of the button                                          |
| onUserSays                 | Happens as soon as the user types something in the chat                                                                                                             | say = the text sent by the user.                                                                      |
| onChatInteractionStarted   | Fired as soon as MyLINK Connect starts rendering the first interaction chat element                                                                                 | None                                                                                                  |
| onChatInteractionCompleted | Fired as soon as interaction rendering is done and control is given back to the user                                                                                | None                                                                                                  |
| onVoiceConfigured          | Fired as soon as MyLINK Connect completes the initialization of languages and voices for text-to-speech                                                             | speechutterance = a SpeechSynthesisUtterance object that will be used to for speech-to-text           |
| onDestroy                  | Fired as soon as the whole MyLINK Connect widget is destroyed and removed from the page contents                                                                    | None                                                                                                  |
| onCalloutDisplay           | Fired when the [callout bubble](https://docs.mylinkconnect.com/basic-concepts/publishing/channels/web/..#display-callout-message-bubble) of the widget is displayed | text = the text to be displayed in the callout bubble.                                                |

The following script implements all of the above events:

```markup
<script [...] src="https://res.xenioo.com/plugin/xenioo.js"></script>
<script>
    xenioowebchat.Start("d07be17d-9be1-4f57-b220-af5559f61f8e", {
		onInit : function( options ){
				console.log( "Starting initialization." );
				console.log( options );
		},
		onReady : function(){
				console.log( "Xenioo chat instance is now ready." );
		},
		onChatClose : function(){
				console.log( "User has closed the chat area." );
		},
		onChatShow : function(){
				console.log( "Chat area is now visible." );
		},
		onChatHide : function(){
				console.log( "Chat area is now hidden." );
		},
		onWidgetClick : function( calloutclicked ){
				console.log( "User clicked Xenioo chat widget." );
		},
		onDataConnection : function(){
				console.log( "Connecting to Xenioo servers." );
		},
		onItemRender : function( obj ){
				console.log( "Rendering item in chat area (check console log for object details)" );
				console.log( obj );
		},
		onElementRender: function( element, obj ){
				console.log( "Rendering item in chat area (check console log for object details)" );
				console.log( obj );
		},
		onButtonClick : function( say, command ){
				console.log( "User clicked '" + say + "' button." );
		},
		onUserSays : function( say ){
				console.log( "User input:" + say );
		},
		onChatInteractionStarted : function(){
				console.log( "Interaction started." );
		},
		onChatInteractionCompleted : function(){
				console.log( "Interaction finished. Control is back to the user." );
		},
		onVoiceConfigured: function( utterance ){
				console.log( "Voice is initialized!" );
		},
		onDestroy : function(){
				console.log( "Chat widget erased removed from page" );
	  },
		onCalloutDisplay: function( text ){
   			console.log( "Callout bubble displayed:" + text );
		}
});
</script>
```

## Functions

To use MyLINK Connect web widget functions all you need to do is refer to the global mylinkconnect*webchat* JavaScript variable that is created automatically by the Web Widget script.

#### isChatOpened()

Returns true if the chat area is visible, otherwise false.

#### openChat()

Open the chat area if closed. If the chat area is already visible, nothing happens.

#### closeChat()

Close the chat area if open. If the chat area is already hidden, nothing happens.

#### toggleChat()

This function will open the chat area if closed or close it if opened.

#### resetChat()

This function will reset the chat area, removing all message bubbles and clearing the current user id. Using this function will create a new conversation on Xenioo but will not reset the chat layout and personalization.

#### scrollCarousel( speed, id, indexmove )

This function will make the carousel specified by **id** move by **speed**. If **speed** is negative, the carousel will scroll to the left otherwise to the right. The active index of the carousel will be the result of the current index value plus **indexmove**.

#### say( text, command )

The say function will send a **text** or **command** to the chatbot. This is exactly as the user writes something or click on a specific button.

**showBubble( text )**

Display the chat widget [callout bubble](https://docs.mylinkconnect.com/basic-concepts/publishing/channels/web/..#display-callout-message-bubble) with the message specified in text. The bubble is displayed only if the chat area is closed.

**hideBubble()**

Hides the currently displayed [callout bubble](https://docs.mylinkconnect.com/basic-concepts/publishing/channels/web/..#display-callout-message-bubble). If no bubble is displayed the command is ignored.

**getVariable( name )**

Returns the value of a conversation variable sent to the client by[ Web Publishing configuration](https://docs.mylinkconnect.com/basic-concepts/publishing/channels/web). Only variables selected for forwarding are available here.\
If the variable is not found, null is returned.

**setVariable( name, value )**

Will add a variable with a given value to the next message sent to MyLINKConnect. Differently from the [Cloud Scripting SetVariable](https://docs.mylinkconnect.com/actions-and-operations/integration/xenioo.bots.actions.base.executescriptaction) this command does not set the variable value right away: a user interaction is required in order to send the data back to the bot.

#### goTo( behavior, interaction, params )

This function will redirect the conversation the the specified **behaviour** and **interaction**. Additionally, one or more **parameters** can be specified. These parameters will be translated to variables sent to the chatbot runtime. The script below shows an example of a goTo call:

```javascript
xenioowebchat.goTo( "My Bot Behaviour", "Bot Interaction Name", 
    { 
      mycustomvariable : "sometest",
      myothervariable : "moretest"
    }
);
```

#### closeFloatContent()

Close the floating content area if open. If the floating content area is already hidden, nothing happens.

#### openFloatContent();

Open the floating content area if closed. If the floating content area is already visible, nothing happens.

#### toggleFloatContent();

This function will open the floating content area if closed or close it if opened.

**showFloatingUrl( { Text, Command } );**

This function will open the floating content area and display the Url set in *Command*. The floating area will have the title set in *Text*. The floating area can be seen only if the chat area is opened.

```javascript
xenioowebchat..showFloatingUrl( 
						{ 
						  Text:"Xenioo Home!!!",							//title
						  Command: "https://www.xenioo.com" 	//target url
						} );
```

#### setVoiceLanguage( language, voice );

This function will change the current voice configuration setting by applying a new language or a new voice to the current utterance instance.\
The following example will change the current language to Italian:

```javascript
xenioowebchat.setVoiceLanguage( "it-IT" );
```

In the following example instead, we're switching to the first available voice on the current browser:

```javascript
xenioowebchat.setVoiceLanguage( null, window.speechSynthesis.getVoices()[0] );
```

Voice changes will take effect starting from the next sentence to be said by the text-to-speech engine.

**destroy();**

This function will stop the Connect chat widget and remove any content generated from the page.
