Table of Contents

Javascript in Landbot v3

Pau Sanchez Updated by Pau Sanchez

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

When testing Javascript be sure to use the 'Share URL' and not 'Preview'

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 these 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

Warning: the URL must be an HTTPS:// otherwise you will get an error that will not allow you to save changes.

To Set the Value of a Javascript variable from of a Landbot Variable

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

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

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

var welcomeinput = "@{welcome}";

console.log(welcomeinput);

Now we can print it:

If you are working strings that contain line breaks or objects that might contain boolean values (true/false) use template literals to set Javascript variables. Example:

var object = `@{array}`;

console.log(object);

To Set the Value of a Landbot variable with Javascript

It is very important to understand that this step (Javascript to Landbot) it ALWAYS needs the 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 by 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 Customs 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>

Other examples:

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 Set Variable block which will contain the QR code and a Buttons block to display the QR:

Here is how it will work:

Open livechat on "exit intent" (add script to parent page)

In this example we trigger the bot to open when the user hovers outside the window, desktop only, and only once.

Here is the code:

<script>
var el = document.createElement('script');
el.text = `document.addEventListener('mouseout', e => {
if (!e.toElement && !e.relatedTarget && !window.exitIntent) {
window.exitIntent = true;
myLandbot.open()
}
});`
document.getElementsByTagName("head")[0].appendChild(el);
</script>

Another example

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

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

This method consists of 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: Trigger a function located in the parent site where the bot is embedded

Let's say that you have a function, that changes the color of the background of your site, depending on the user interaction with your bot. And to do that you have a function like this in the parent site (window scope):

function changeBackgroundColor(color){
document.body.style.background = color;
}

Then, to trigger this event, and change the color from Landbot, you will add this in a code Block:

window.changeBackgroundColor("blue")

Even, you can use Landbot variables as a parameter to be passed. So if you had in the variable @color, the value, you can pass it like this:

window.changeBackgroundColor("@{color}")

Here is how it will look like in the builder:

And here is how the user will see it:

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

On some occasions, we might need to pass information between Landbot and the site where the bot is embedded or another 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 on 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>

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 a 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>

API Custom Data

Another 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 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 with 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 one click on the 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?

Landbot Developer's Documentation

Contact