JavaScript API
How to leverage JavaScript to read/write data to Spara.
Reading Javascript events from Spara
Spara's JavaScript API exposes two events to the DOM:
Spara.onSparaLoad()fires when Spara's embed script finishes executingSpara.onUserMessageSent()fires when a lead sends message to Spara
These can be used however you like. For example, by pushing these events to your window's data layer for ingestion by Google Analytics.
To access these Javascript events, you will need to add an additional script to your website's <head>:
<script type="text/javascript" src="https://app.spara.co/embed-<app_id>.js"></script>
<script>
Spara = {
onSparaLoad: () => {
console.log("Spara is loaded! 🎬");
},
onUserMessageSent: () => {
console.log("User sent a message to Spara 💬");
},
}
</script>Writing information to Spara using Javascript
Spara's Javascript API exposes methods to write information to Spara Lead objects. For more information on how leads are represented in our database see our documentation on Lead Schema.
SparaActions.setFields accepts a dictionary of arbitrary key/value pairs assigned to the current website visitor. For example:
SparaActions.setFields({
acme_uuid: '1234567', // This is an arbitrary field and value
experiment_group: 'control'
}To specifically send Spara information on page load, you will need to add an additional Javascript snippet immediately after initializing Spara's Javascript embed.
Here is a full example, which sets the current visitor's "ACME uuid" field:
<script type="text/javascript" src="https://app.spara.co/embed-<app_id>.js"></script>
<script>
Spara = {
fields: {
acme_uuid: '1234567' // This is an arbitrary field and value
}
}
</script>Note on Query Parameters
A reminder that Spara automatically ingests all query parameters from your webpages. So another way to See Query Parametersfor more information
Opening Spara Navigator using Javascript
In addition, Spara provides a JS function to dynamically open Spara Navigator: SparaAction.openChat It has 2 options: aiMessage & userMessage.
For example, SparaActions.openChat({ userMessage: 'Hi' }) opens Spara Navigator with the user sending a message "Hi."
In another example, SparaActions.openChat({ aiMessage: 'How can I help?' }) opens Spara Navigator with Spara's AI saying "How can I help" to start the thread. Note that aiMessage will only create a new message for an empty thread.
How to open Spara Navigator when a user clicks a CTA
A common interaction is for Spara Navigator to load in a "closed" state, but "magically" open when a website visitor clicks a CTA.
To accomplish this:
Set Navigator to load in Spara Navigator. Website visitors will only see the bottom right avatar on page load.
Write a brief Javascript snippet that opens Spara Navigator when a CTA is clicked.
// Example assumes CTA button has id="cta"
document.getElementById('cta')?.addEventListener('click', () => {
SparaActions.openChat({ aiMessage: 'How can I help?' });
});Last updated