Table of Contents

Landbot v3 JavaScript Integration

Pau Sanchez Updated by Pau Sanchez

JavaScript in Landbot v3 is only available for web chatbots. It's not compatible with WhatsApp or Messenger bots.

When testing JavaScript, be sure to use 'Share URL' and not 'Preview'.

Web chatbots offer you the possibility to integrate JavaScript into Landbot v3 to create more dynamic interactions and make the most of Landbot for your website. Let's have a look at all the possible things you can do with this integration.

Using the JavaScript Code Block in Landbot

Sometimes, we want to trigger some JavaScript functions during the chatbot flow. For that, you can use the JavaScript Code block to trigger scripts at specific points in the flow.

The code in these blocks will be active only when the visitor passes through this point of the conversation. 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 HTTPS:// otherwise you will get an error that will not allow you to save changes.

Using JavaScript with Landbot Fields

You can use Landbot JavaScript to interact with Landbot Fields, such as utilizing template literals for complex data formatting or leveraging the Landbot API to assign variables based on user interactions within workflows.

Setting JavaScript Variables from Landbot Variables

Let's say you want to print on the console the "welcome" Field.

  1. First, we are going to set the value of a JavaScript Field called 'welcomeinput' to the value of the Landbot Field @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);

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

In the example below, we are going to set the value of the Landbot Field @var to 3000.

  1. We use the code block to set the value of a variable (in this example, the Landbot Field is called "@var"):
this.setCustomData({ var: 3000 });
  1. We need to add an input for the user to 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 new values directly to Landbot Fields.

Generating the value of a Landbot Field could be as simple as in the example below, where we make sure numbers have two decimals and transform the numeric Landbot Field @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 Field 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 Field won't display in any of the Fields' lists, unless you create it manually

Example: Encode user input

How to encode a variable

Linking Code Blocks with Bot Scripts

You can use the Design > Custom Code section to enable interaction between scripts, allowing seamless communication between code blocks and bot scripts. By leveraging Landbot JavaScript, you can 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}")

  1. 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>

Other examples:

Adding Third-Party Scripts to Your Bot

With Landbot Integrations, you can, for example, load a style or a script in your embedding page as soon as the bot loads and trigger it whenever you want with a code block.

Here is how you can add such a 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:

Example: Open live chat 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

Landbot's integrations make connecting your favorite tools easy, enhancing automation, and tackling complex business challenges. You can explore more integrations here.

Connecting Landbot with Your Embedding Page

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. 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")

You can even use Landbot Fields as a parameter to be passed. So if you had the value in the Field @color, you can pass it like this:

window.changeBackgroundColor("@{color}")

Here is what 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).

Sharing Data Between Landbot and the Embedding Page

On some occasions, we might need to pass information between Landbot and the site where the bot is embedded or the way around or even both ways. 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 more flexible alternative that 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.

Controlling Embedded Bots from the Parent Page

You can use Landbot JavaScript to control bot behavior from the parent page. Let's have a look at some examples.

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 method, 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 the bot and "Send" a user to a specific point in the flow with Javascript

Here is the sample set up inside the builder:

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

Note: Take note that 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.

  1. Now, in the parent page, we need to set up the event listener to trigger which 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 method, please check here.

Here is an example:

Start Customizing Your Landbot v3 with JavaScript Today

Using JavaScript in Landbot v3 unlocks enhanced bot functionality, improves workflow efficiency, and enables advanced customization to tailor interactions to your needs.

For advanced JavaScript, please check our Landbot SDK and developer documentation here.

Was this article helpful?

Javascript in WhatsApp

Different ways to format numbers with JS

Contact