1

I have an Angular-CLI application (Angular 6) which is being launched from another external page. So at first index.html is being displayed. I can send data asynchronously from the external page to index.html by using postMessage method. My question is how to pass this data to my Angular app. I have two problems:

  • First one is main.ts is launched immediately and by that time I haven't yet received the data sent with postMessage. So, how can I defer main.ts?

  • Second thing is how to send data to main.ts and how to make it available to my application?

index.html

<body>
  <script>

    window.onload = function () {
      window.parent.postMessage("Loaded", "*");
    }

    window.addEventListener("message",
      function(event) {
        if (event.origin !== 'http://localhost:8080') {
          return;
        }
        console.log("Yes!!!", event.data);
      });

  </script>
  <app-root>Loading...</app-root>
</body>

main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

export function getBaseUrl() {
  return document.getElementsByTagName('base')[0].href;
}

const providers = [
  { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic(providers).bootstrapModule(AppModule)
  .catch(err => console.log(err));
Unknown developer
  • 5,414
  • 13
  • 52
  • 100
  • _"how can I defer main.ts"_ Why would you want to defer the execution? You can wait for the message and then bootstrap the application right in main.ts. – a better oliver May 29 '18 at 12:13
  • Possible duplicate of [Angular 2 window.postmessage](https://stackoverflow.com/questions/41444343/angular-2-window-postmessage) – Jens Habegger May 29 '18 at 12:39

0 Answers0