BobbyLinux
BobbyLinux

Reputation: 150

Angular 6 - call Angular function from external js file

Recently I'm rewriting a plan JS app with Angular 6.

The old stuff work like this:

file js inside a iframe that call "parent.update_track()" function defined into main.js file into iframe container.

that's not work in Angular when app run on production, the response is: TypeError: parent.update_track is not a function.

so how can I call this function "update_track()" declared into a ts file in a component from an external js file contained into iFrame?

Upvotes: 1

Views: 1472

Answers (1)

galvan
galvan

Reputation: 7466

You can use post message functionality.

So in your iframe you can just call the opener window (the parent) to post message, for more info you can use this reference

Then in the angular app (the parent) you can use the following listener:

@HostListener('window:message',['$event'])
onMessage(e) {
  if (e.origin!="http://localhost:4200") {
     return false;
  }

  alert('here i am');
}

}

Note: you should change the e.origin test to support both local env and production.

Upvotes: 3

Related Questions