Angular 2 window.postmessage

后端 未结 3 2148
时光取名叫无心
时光取名叫无心 2020-12-30 06:01

I\'m working on an eCommerce application in Angular 2 with a node and express api backend. I\'m currently working on the social login section where I am using passport-faceb

相关标签:
3条回答
  • 2020-12-30 06:44

    You could also use the @HostListener() function decorator:

    @HostListener('window:message', ['$event'])
    onMessage(event) {
      this.receiveMessage(event);
    }
    
    0 讨论(0)
  • 2020-12-30 06:45

    Combining @PierreDuc's .bind(this) technique and @Mikeumus's comment:

    import {Component, OnDestroy, Renderer2} from '@angular/core';
    
    @Component({
      selector: 'my-component',
      templateUrl: './my_component.ng.html',
    })
    export class MyComponent implements OnDestroy {
      stopListening: Function;
    
      constructor(private renderer: Renderer2) {
        this.stopListening =
            renderer.listen('window', 'message', this.handleMessage.bind(this));
      }
    
      handleMessage(event: Event) {
        const message = event as MessageEvent;
    
        // Only trust messages from the below origin.
        if (message.origin !== 'http://example.com:8080') return;
    
        console.log(message.data);
      }
    
      ngOnDestroy() {
        this.stopListening();
      }
    }
    

    You can still directly do this if you prefer:

    this.stopListening =
        renderer.listen('window', 'message', (even: Event) => { ... });
    

    You can test it by commenting out the origin check and writing this in the developer JavaScript console:

    window.postMessage("test message data", "http://localhost:8080")
    

    Update the 2nd arg to be the URL of the page you are currently on. This command makes the page think it received a message from itself.

    0 讨论(0)
  • 2020-12-30 06:53

    You should change the way you declare the eventListener (by using bind(this) or an anonymous function, or change the way you declare your eventHandlers:

    bind(this):

    constructor(private _authService: AuthService, private _router: Router) { 
       if (window.addEventListener) {
         window.addEventListener("message", this.receiveMessage.bind(this), false);
       } else {
          (<any>window).attachEvent("onmessage", this.receiveMessage.bind(this));
       }
    }
    

    anonymous function

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

    different declaration of eventHandler

    receiveMessage: any = (event: any) =>  {
      //...
    }
    

    Take your pick :) With the last option it is easy to detach the eventListener

    0 讨论(0)
提交回复
热议问题