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 programaticallyvar 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/componentdocument.body.appendChild(script);// or in a template<scriptasyncsrc=`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.
asyncfunctioninsertEmbedStory() {constinstance=awaitTcTcEmbed.initialize('{SDK_TOKEN}');awaitinstance.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' });}
asyncfunctioninsertEmbedStory() {constinstance=awaitTcTcEmbed.initialize('{SDK_TOKEN}');awaitinstance.insertEmbedById('{EMBED_ID}',document.getElementById('embed-story-container'), { token:'{USER_EMBED_TOKEN}', } );constembed=awaitinstance.get('{EMBED_ID}');embed.setExtraVariables({ commentary:'This is a commentary set by using the SDK function but for a specific embed' });}