Open the website widget with a button

Besides copying and pasting the code snippet to place the Website Widget on your website, there is another way to display the Website Widget, namely opening it by clicking a button.

In this article, we created an example that explains exactly how this works below. Follow the steps below.

 

1. Create a reference to an element in the DOM

var trigger = document.getElementById('chatbotTrigger');

 

2. Adding an eventlistner

The eventlistner is fired as soon as the trigger is clicked. In the source code, you still need to change the value of the variable: window['Watermelon'].key.

trigger.addEventListener('click', function() {
window['Watermelon'] = window['Watermelon'] || {};
window['Watermelon'].key = 'YOUR WEBSITE WIDGET KEY HERE';
window['Watermelon'].toggled = true;

localStorage.setItem('app.conversation.toggled', 'true');
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'https://wm-livechat-2-prod-dot-watermelonmessenger.appspot.com/assets/js/wm_plugin.js';
document.getElementsByTagName('script')[0].appendChild(script);
})

 


3. Example

Below is an example of how you might use it. 

<html lang="en">
<head>
<title>Website widget</title>
</head>
<body>
<button id="chatbotTrigger">Open Website widget</button>
<script>
(function(){
var trigger = document.getElementById('chatbotTrigger');

function openChatBot() {
window['Watermelon'] = window['Watermelon'] || {};
window['Watermelon'].key = 'YOUR WEBSITE WIDGET KEY HERE';
window['Watermelon'].toggled = true;

localStorage.setItem('app.conversation.toggled', 'true');
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = 'https://wm-livechat-2-prod-dot-watermelonmessenger.appspot.com/assets/js/wm_plugin.js';
document.getElementsByTagName('script')[0].appendChild(script);
}

trigger.addEventListener('click', function() {
// If there is not chatbot open then open one else remove it and add it again
if (!document.getElementById('wm-livechat')) {
openChatBot();
} else {
const wmLiveChat = document.getElementById('wm-livechat');
document.getElementsByTagName('body')[0].removeChild(wmLiveChat);
openChatBot();
}
})
})();
</script>
</body>
</html>