Passing parameters to the chat widget
When a website has a bot in the chat widget, it can communicate with the widget by passing it arbitrary data, which the bot can then access in order to “know” what is happening on the website.
Passing parameters can be done in two ways:
When the chat widget is loaded
Site script setup
In order to pass parameters from the website, the required page should contain a script defining a global variable juswidgetVariables
. This should be an object with a start
property, which in turn should contain a nested object with all the necessary key-value pairs:
<script>
window.juswidgetVariables = {
start: {
id: 58,
name: "Johanna"
}
};
</script>
Bot script setup
When the chat widget is launched, a /start
message is automatically sent to the bot. However, if juswidgetVariables.start
is defined, this object is serialized as JSON and appended to the /start
message after a space character. Let’s write a simple mock state for handling the dialog beginning:
state: Start
q!: $regex</start> *
a: You said: {{$parseTree.text}}
If we now launch the bot on a page containing the script defined above, the following message will be displayed:
The object received by the bot can be processed in order to extract the necessary data.
state: Start
q!: $regex</start> [$regex<\{.*\}>]
script:
if ($parseTree.text.length > "/start".length) {
$session.startData = JSON.parse($parseTree.text.substr("/start".length + 1));
}
if: $session.startData
a: Hi, {{$session.startData.name}}!
else:
a: Hi!
The following XML test passes for the script above:
<test>
<test-case>
<q>/start {"id":50,"name":"Johanna"}</q>
<a>Hi, Johanna!</a>
</test-case>
<test-case>
<q>/start</q>
<a>Hi!</a>
</test-case>
</test>
On every new message
To pass parameters to the bot on any incoming message, set up either a JustWidgetSendRawData
function returning the object with the appropriate data or this object itself as a JustWidgetRawParams
variable:
<script>
window.JustWidgetSendRawData = function() {
return {
currentUrl: window.location.href
};
};
// This code does the same as the code above
window.JustWidgetRawParams = {
currentUrl: window.location.href
};
</script>
<script>
document.getElementsByTagName("iframe")[0].contentWindow.JustWidgetRawParams = {
currentUrl: window.location.href
};
</script>
$request.data.JustWidgetRawParams
.