vishnuk
vishnuk

Reputation: 101

Angular 5 window.postmessage

I'm working on an application in Angular 6 with a Springboot API backend. I'm currently working on an application where I am loading an iframe. In the child Document when there is a submit button when I click the button an API is called in the child Document upon on response from that API I need to grab the response from that API. Does anyone have any suggestions?

Below is my component in typescript. I can include other codes if need be but I don't know that it is needed.

Here is the Code.............

import { Component, OnInit, ViewChild, HostListener, ElementRef } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-auth-exception',
  templateUrl: './auth-exception.component.html',
  styleUrls: ['./auth-exception.component.css']
})
export class AuthExceptionComponent implements OnInit {


  constructor() {

    if (window.addEventListener) {
      window.addEventListener('message', this.receiveMessage.bind(this), false);
    } else {
      (<any>window).attachEvent('onmessage', this.receiveMessage.bind(this));
    }
  }

  ngOnInit() {
    window.addEventListener('message', () => {
      this.receiveMessage();
   }, false);
  }

  setEventListener() {
    const eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';
    const eventer = window[eventMethod];
    console.log('eventer=' + eventer);
    const messageEvent = eventMethod === 'attachEvent' ? 'onmessage' : 'message';
    console.log(messageEvent + '---' + eventMethod);
    eventer(messageEvent, this.receiveMessage, false);
  }


  receiveMessage: any = (event: any) =>  {
    const origin = event.origin || event.originalEvent.origin;
    if (origin === '') {
      if (event.data !== null && typeof event.data === 'object') {
        console.log('Data' + event.data['']);
      } else {
        const RefObject = JSON.parse(event.data);
        console.log(RefObject);
        this.RefValue = RefObject.value;
      }
    }
  }

}

Upvotes: 9

Views: 14096

Answers (1)

Damsorian
Damsorian

Reputation: 1694

you can use HostListener

@HostListener('window:message', ['$event']) onPostMessage(event) {
    // here your code
}

Upvotes: 16

Related Questions