In some cases, you may need to pass variables to your Toucan embed without predefining them in the Toucan platform. This allows flexibility depending on the specific context of your application.
Passing Variables via Embed Script
You can add variables to your embed script URL like this:
For object or array types, ensure variables are JSON-encoded. Use JSON.stringify to properly format complex variables.
Handling Multiple Variables
When you need to pass numerous variables, including objects and arrays, it’s best to package them under a single extrakey:
var formattedVariables = JSON.stringify({
extra: { // super important to put all your variables under the "extra" key
varA: "simple_string",
varB: 42,
varC: {
childrenKey: "str"
},
varD: ["itemA", "itemB"]
}
})
// then used it programatically
var script = document.createElement('script');
script.src = `https://myinstance.toucantoco.com/scripts/embedLauncher.js?id=EMBED_ID&variables=${formattedVariables}`
// append it to your body or you parent div/component
document.body.appendChild(script);
// or in a template
<script async src=`https://myinstance.toucantoco.com/scripts/embedLauncher.js?id=EMBED_ID&variables=${formattedVariables}` type="text/javascript"></script>
Example
Using Variables in Your Story Configuration
After setting up your variables, you can access them in the configuration of your story. With extraVariables, you can dynamically insert context-driven content into your story. This supports default values to avoid empty states.. For example, you can set a contextual commentary.
Note that you can display a default value to avoid that state.
You should now have default value interpolated.
Dynamically Updating extraVariables
With our SDK, you can update extraVariables dynamically to connect them with UI components in your application.
async function insertEmbedStory() {
const instance = await TcTcEmbed.initialize('{SDK_TOKEN}');
await instance.insertEmbedById(
'{EMBED_ID}',
document.getElementById('embed-story-container'),
{
token: '{USER_EMBED_TOKEN}',
}
);
instance.setExtraVariablesForAllEmbeds({ commentary: 'This is a commentary set by using the SDK function' });
}
async function insertEmbedStory() {
const instance = await TcTcEmbed.initialize('{SDK_TOKEN}');
await instance.insertEmbedById(
'{EMBED_ID}',
document.getElementById('embed-story-container'),
{
token: '{USER_EMBED_TOKEN}',
}
);
const embed = await instance.get('{EMBED_ID}');
embed.setExtraVariables({ commentary: 'This is a commentary set by using the SDK function but for a specific embed' });
}