angularfreshdesk

How can I add a Freshdesk widget during runtime in Angular?


I'm using Angular 9 and am trying to add a Freshdesk widget to my app. The snippet for that widget that looks like this:

<script>
window.fwSettings={
'widget_id': <MY PERSONAL ID>,
'locale': 'en'
};
!function(){if("function"!=typeof window.FreshworksWidget){var n=function(){n.q.push(arguments)};n.q=[],window.FreshworksWidget=n}}() 

If I add the snippet directly into my index.html file it works fine but I want to be able to programatically set the locale property to whatever language the current user has chosen.

That means this snippet needs to be added during runtime, but I have no idea how to it in Angular.

Any ideas?


Solution

  • I solved it. In my app.component.ts I put the snippet in a function after I've loaded my apps locale:

    loadFreshDesk(locale): void {
       window.fwSettings = {
          widget_id: MY_WIDGET_ID,
          locale: MY_FRESH_DESK_LOCALE,
        };
    
        !(function () {
          if ('function' !== typeof window.FreshworksWidget) {
            const n = function () {
              n.q.push(arguments);
            };
            (n.q = []), (window.FreshworksWidget = n);
          }
        })();
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = 'https://widget.freshworks.com/widgets/MY_WIDGET_ID.js';
        document.getElementsByTagName('head')[0].appendChild(script);
    }