angularangular6localhostgoogle-castdynamic-script-loading

Adding external library to my Angular 6 project only works when I'm running in localhost


I dynamically added the Chrome Api Library (from https://www.gstatic.com/cv/js/sender/v1/cast_sender.js) to my project, and works as expected when I run using localhost:4200. However it doesn't work when I run using my IP : 192.168.0.144:4200. In this case the app runs, but the Chrome lib doesn't work.

This is my code:

  cast: any;

  constructor() {

  }

  ngOnInit(): void {
    console.log('ngOnInit()');

    const script = window['document'].createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.setAttribute('src', 'https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1');
    window['document'].body.appendChild(script);

    window['__onGCastApiAvailable'] = (isAvailable) => {
      if (isAvailable) {
        this.cast = window['chrome'].cast;
        const sessionRequest = new this.cast.SessionRequest('<MY_APP_ID>');
        const apiConfig = new this.cast.ApiConfig(sessionRequest,
          s => { },
          status => { if (status === this.cast.ReceiverAvailability.AVAILABLE) { } }
        );
        const x = this.cast.initialize(apiConfig, this.onInitSuccess, this.onInitError);
      } else {
        console.log('CAST API is not available !!');
      }
    };

  }

Works with localhost.

chrome console(localhost)

NOT working with the IP...

chrome console(ip)

I've already tried to add the lib in the index.html, instead of dynamically in the component, and got the same result. I thought could be a CORS issue. Then I tried to config this proxy, without success:

{
  "/v1": {
    "target": "https://www.gstatic.com/cv/js/sender/",
    "secure": false,
    "changeOrigin": true
  }
}

And changing this line:

script.setAttribute('src', '/v1/cast_sender.js?loadCastFramework=1');

But only localhost keeps working...Help !


Solution

  • I finally solved this !! Chrome sender apps need to support HTTPS. So, I made a tunel with ngrok and worked.