Using Discourse variables to personalize embedded Typeform

Here is my (somewhat clumsy) solution, in case it helps someone. I added this code under Admin > Customize > Themes > Edit CSS/HTML > /head:

    <script type="text/discourse-plugin" version="0.8">
        api.decorateCooked($elem => {
            var i, j;
            var selector = 'https://example.typeform.com';
            // seems like this should work but it doesn't:
            // var typeforms = $elem[0].querySelectorAll('src^=[' + selector + ']');
            var ps = $elem[0].querySelectorAll('p');
            for (i=0; i<ps.length; i++) {
                p = ps[i];
                var iframes = p.querySelectorAll('iframe');
                for (j=0; j<iframes.length; j++) {
                    var iframe = iframes[j];
                    if (iframe.src.startsWith(selector)) {
                        var oldsrc = iframe.getAttribute('src');
                        var username = api.getCurrentUser()['username'];
                        var newsrc = oldsrc + '?username=' + username;
                        iframe.setAttribute('src', newsrc);
                    }
                }
            }
        });
    </script>

Then add a Hidden Field “username” in your Typeform. The username can be used in your form, and will also be sent to the destination (integrations or webhook) when the user hits Submit.

When you get the Typeform link to embed in Discourse, it will be something like:

https://example.typeform.com/to/dr8oAa?username=xxxxx

Remove the ?username=xxxxx before embedding; the js above will add it back, with the proper Discourse username.

1 Like