简体   繁体   English

在 React 组件中收听 window.onmessage

[英]Listen to window.onmessage in React Component

I'm trying to listen for a postmessage in my react class.我正在尝试在我的反应 class 中收听帖子消息。 It isn't working.它不工作。

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleMessage = this.handleMessage.bind(this);
  }
  componentDidMount(){
    window.addEventListener("onmessage", this.handleMessage);
  }
  componentWillUnmount() {
    window.removeEventListener('onmessage', this.handleMessage);
  }
  handleMessage(e){
    console.log('me?')
  }
}

I send the message like this:我这样发送消息:

window.opener.postMessage('a message', '*');

I know the message is getting to the window, because I can successfully listen to it in the plain JS file that loads the react app.我知道消息正在发送到 window,因为我可以在加载反应应用程序的普通 JS 文件中成功收听它。 However listening for it in react as above does not work.但是,在上面的反应中听它不起作用。

Why isn't my listener every being triggered, how can I debug it?为什么我的监听器不是每次都被触发,我该如何调试它?

The event's name should be message and not onmessage :事件的名称应该是message而不是onmessage

 window.addEventListener("message", this.handleMessage);

See: The dispatched event请参阅: 已调度的事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM