Table of Contents

Javascript in Landbot v3

Pau Sanchez Updated by Pau Sanchez

ONLY AVAILABLE FOR WEB LANDBOTS - Not compatible with Whatsapp or Messenger

Web Landbots offer the possibility to use Javascript in a large number of ways to make the most of Landbot and work together with your flow and your site. Here is a list of possible things you can do:

To trigger code inside the bot in specific steps of the flow: Code (Javascript) block

Sometimes we want to trigger some Javascript functions during the flow, here is where we can do it.

The code in this blocks will be active only when the visitor passes through this point. So functions in the block don't have a global scope.

Do not use <script> tags

This code will be embedded inside <script> </script> tags, so there is no need to add them, as you can see below. In this example, when the visitor passes through this block, a "hello world" will be printed in the console

To Set Value to a Javascript variable out of a Landbot Variable

Let's say you want to print on console the variable welcome

  1. First we are going to set a the value of a Landbot variable @welcome to a Javascript variable called welcomeinput

  1. Now we add the code to show in the console

var welcomeinput = "@{welcome}"

console.log(welcomeinput)

Now we can print it:

To Set Value to a Landbot variable with Javascript

It is very important to understand that this step (Javascript to Landbot) it ALWAYS needs an input of the visitor, before the Javascript value is available in the Landbot variable.STEPS:1 Javascript variable value => 2 Landbot custom-data SDK => 3 USER INPUT (button, text...) => 4 Landbot variable Javascript value assigned & available to use

In the example below, we are going to give the Landbot variable called @var, the value of 3000

  1. We use the code block to set the value of a variable (in this example the Landbot variable is called "@var") :
this.setCustomData({ var: 3000 });
  1. We need to add an input for the user, to pass the complete the process before the value is available in Landbot scope (NOT OPTIONAL)
  1. And finally we set up a block, where we will display the new Landbot value
As an alternative to this approach you can do this: Use Google Cloud Functions to set directly new values to Landbot variables

Generating the value of a Landbot variable could be as simple as in the example below where we make sure numbers have 2 decimals, and transform the numeric Landbot variable @value :

this.setCustomData({ value: (Math.round("@{value}"*100)/100).toFixed(2) });

Example: Set a variable right on the loading time of the bot

In this example we set a value in a Landbot variable called @randomnumber. To do that we will use the section Add JS (Design > Custom Code)

Bear in mind this value will be available AFTER the user interacts with the Welcome Message.
<script>
var landbotScope = this;
this
.onLoad(function(){
const randomNumber = Math.floor((Math.random() * 9999) + 1);
landbotScope.setCustomData({randomnumber:randomNumber})
})
</script>

This variable won't display in any of the variables' lists, unless you create it manually

Example: Encode user input

How to encode a variable

To communicate between a Code block and Bot Body (Design > Custom Code section)

In the Design > Custom Code > Add JS section, you are able to add code, that:

- Is loaded as soon as the bot is loaded

- Can be triggered from Code blocks independently

- It is not compatible with Jump to

Example: Pass value to body scope from code block and log it

Here is an example of how you can communicate between the bot (code block) with a variable in the Design/Custom Code section:

  1. Code block:
this.window.setVariable("@{welcome}")

And in the Custom Code section:

<script>
  var landbotScope = this;
this.onLoad(function() {
    landbotScope.window.variableName = null;
    landbotScope.window.setVariable = function(data) {
      landbotScope.window.variableName = data;
      console.log(landbotScope.window.variableName);
    }
  });
</script>

To add a script snippet in the embedding page (3rd party JS library)

Maybe we are interested to load a style or a script in our embedding page, as soon as the bot loads, and trigger it whenever we want with a code block.

Here is how you can add such script tag:

<script>
var el = document.createElement('script');
el.setAttribute('src', 'https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js');
document.getElementsByTagName("head")[0].appendChild(el);
</script>

We will find this after in the Window scope, of the embedding page.

Example: Generate QR code based on user input
  1. As displayed above we add the following code in the Custom Code section:
    This will allow us to use this bot, embedded or not.
    <script>
    var el = document.createElement('script');
    el.setAttribute('src', 'https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js');
    document.getElementsByTagName("head")[0].appendChild(el);
    </script>
    <script>
    var landbotScope = this;
    this.generateQr = function(data){
    setTimeout(function(){
    var elementtag = landbotScope.document.getElementById('qrcode')
    this.printQR = new QRCode(elementtag, data)
    },1000)}
    </script>
  2. Then in the builder we create a Question Text, where we can gather the url that we are going to use to generate the QR code:
  3. After the Question Text we will add a Code block that will trigger the QR, with some delay enough so the following block is available
  4. After that, we just need to use a Send Message block where it will contain the QR code:

Here is how it will work:

Other example

Add a Chart (with Chart JS library) in your Landbot

To communicate between Landbot and the the Embedding Page (window scope)

This method consists on using the Window scope to call variables and functions in the parent site in this simple way, using the Code block. This is the best way for example to track events with systems like Google Tag Manager

Example: Redirect user

Like in this example, where we can redirect to another url in the same tab:

window.location.href = 'https://www.landbot.io'

This method is also valid for not embedded Landbots (native)

To communicate between the Embedding Page to Landbot

In some occasions we might need to pass information between Landbot and the site where the bot is embedded or other way round or even both ways. In this article we are going to show you how to do this. Bear in mind that this is only applicable to embedded Landbots, and cannot be tested in the preview page.

There are different methods to pass such information:

Embed Snippet Custom Data

Here we add the "customData", key to the embed snippet like in the example below, where we are giving values to the variables @name, @year and @heroes.

<script src="https://static.landbot.io/landbot-3/landbot-3.js"></script>
<script>
var myLandbot = new Landbot.Livechat({
configUrl: 'https://...',
customData: {
name: 'Avengers',
year: 2012,
heroes: [
'Ironman',
'Captain America',
'Hulk',
'Thor',
'Black Widow',
'Hawkeye',
],
},
});
</script>

Obviously you can also assign variables instead of static values:

<script>
var userName = 'Avengers';
var userYear = 2012;
var userHeroes = [
'Ironman',
'Captain America',
'Hulk',
'Thor',
'Black Widow',
'Hawkeye',
]
</script>

<script src="https://static.landbot.io/landbot-3/landbot-3.js"></script>
<script>
var myLandbot = new Landbot.Livechat({
configUrl: 'https://...',
customData: {
name: userName,
year: userYear,
heroes: userHeroes,
},
});
</script>

This way, the variable will be available already in the Welcome Message if needed.

Embed Snippet Url Params
Only use this method for string values. And make sure the value is encoded

Here we use a combination of the url and the Hidden Fields functionality:

<script src="https://static.landbot.io/landbot-3/landbot-3.js"></script>
<script>
var myLandbot = new Landbot.Livechat({
configUrl: 'https://chats.landbot.io/v3/H-X-X/index.json?name=Avengers'
});
</script>

And make sure in the Settings > Hidden Fields section the variable (in this case @name) is ready:

This way, the variable will be available already in the Welcome Message if needed.

Custom Data method (setCustomData)

This a handy method in case you need to pass the information to the bot, once the bot is already loaded and you cannot use the embed snippet.

In the example below we assign to the variable @heroes an array as value


<script src="https://static.landbot.io/landbot-3/landbot-3.js"></script>

<script>
var myLandbot = new Landbot.Livechat({
configUrl: 'https://...'});
</script>

<script>
myLandbot.setCustomData({heroes:[
'Ironman',
'Captain America',
'Hulk',
'Thor',
'Black Widow',
'Hawkeye',
]})
</script>

Alternative methods to Javascript

Hidden Fields (URL params)

Other way to pass variables to your Landbot instead of using Javascript, would be via Hidden Fields, it means using the URL parameters. You can set them up in the Hidden Fields section

For more information please check this article

API Custom Data

A other alternative that is more flexible and might be useful for very specific cases would be to pass the values via API using the CustomerFields method, for more information please check here

In case you need further information about how to handle Javascript inside Landbot, please check this article or our dev docs

To trigger actions in Embedded bots from the container page

You can also trigger a different number of actions like in the examples below

Open LiveChat on click of a button

Below you can find the code you need to trigger and open your landbot, embedded as a LiveChat or Pop up mode, by clicking a button.

<html> 
<body>
<div id="wrapper">
<button class="openbot">Open Bot</button>
</div>

<script type ="text/javascript" src="https://static.landbot.io/landbot-3/landbot-3.0.0.js"></script>
<script>
var myLandbotpop = new Landbot.Popup({
configUrl: 'https://chats.landbot.io/v3/H-642181-Q42D49PVMDCXYYL8/index.json'
});

var buttonOpen = document.getElementsByClassName("openbot")[0];
buttonOpen.addEventListener('click', (event) => {
event.preventDefault();
myLandbotpop.open()
});
</script>
</body>
</html>

As you can see we are using the method "open()" to open the bot. For more information, about this methods, please check here

To hide the widget, you must add the code below in the Design / Advanced / Add CSS section:


.LivechatLauncher{
display: none
}

Open LiveChat and trigger specific flow

With onclick in parent page, we will open bot and "Send" a user to a specific point in the flow with Javascript

Here is the sample set up inside in the builder:

1. We will use Global Keywords, to set up the flows where we want to redirect the user.

Note: Take note of the content of the Global Keyword has to match the payload key of the message to be sent, as you can see in the next example.

2. Now in the parent page, we need to set up the event listener to trigger, that will open the bot and move the user to the desired node

myLandbot.onLoad(function(){

document.getElementsByClassName("openbot")[0].addEventListener("click", function(event){
event.preventDefault()
myLandbot.open();
setTimeout(function(){
myLandbot.sendMessage({ type: 'button', message: 'Go to Step 1', payload: '#1' })
},500)
});

As you can see we are using two methods "onLoad" (to trigger any desired function once the bot is loaded) and "open" (to open the bot). For more information, about this methods, please check here

Here is an example:

Landbot 3 SDK

For advanced Javascript, please check our developers documentation here

How did we do?

APIs

MessageHooks - Landbot Webhooks

Contact