crrlos
crrlos

Reputation: 1236

How to move code from index.html to component?

I had the code below placed in the index.html and it works.

<!-- Smartsupp Live Chat script -->
<script type="text/javascript">
    var _smartsupp = _smartsupp || {};
    _smartsupp.key = '';
    window.smartsupp ||
        (function (d) {
            var s,
                c,
                o = (smartsupp = function () {
                    o._.push(arguments);
                });
            o._ = [];
            s = d.getElementsByTagName('script')[0];
            c = d.createElement('script');
            c.type = 'text/javascript';
            c.charset = 'utf-8';
            c.async = true;
            c.src = 'https://www.smartsuppchat.com/loader.js?';
            s.parentNode.insertBefore(c, s);
        })(document);
</script>

How can I move that code to be executed from inside a component?

I tried put the code inside a function for example ngAfterViewInit() but I get errors like Property 'smartsupp' does not exist on type 'Window & typeof globalThis'.

export class AppComponent  {
  

  ngAfterViewinit(){

    var _smartsupp = _smartsupp || {};
        _smartsupp.key = '';
        window.smartsupp ||
            (function (d) {
                var s,
                    c,
                    o = (smartsupp = function () {
                        o._.push(arguments);
                    });
                o._ = [];
                s = d.getElementsByTagName('script')[0];
                c = d.createElement('script');
                c.type = 'text/javascript';
                c.charset = 'utf-8';
                c.async = true;
                c.src = 'https://www.smartsuppchat.com/loader.js?';
                s.parentNode.insertBefore(c, s);
            })(document);
 
  }

}

Upvotes: 0

Views: 314

Answers (1)

elmetni
elmetni

Reputation: 104

You can move your code to a js file startup.js

and then include the script on your TS file in ngInit

var script = document.createElement('script');
script.src = "assets/startup.js";
document.head.appendChild(script);

and in your script you have smartsupp object added in window

so you can make a condition on it to make sure it s loaded

    if(window && window.smartsupp)
    {
      // do something 
    }

Upvotes: 1

Related Questions