iframe src页面内容变化,需要关闭iframe所在弹窗

395 阅读1分钟

业务: 弹窗内嵌套iframe,需要在倒计时结束时,关闭弹窗

image.png

实现代码: 当倒计时为0时通过 postMessage 向父级窗口发送消息 "closePopup"。然后,在外层弹窗页面中,通过监听 message 事件来接收到该消息,并执行关闭弹窗的逻辑。

父组件中 this 绑定指向组件实例需关注,漏写会报错,导致关闭弹窗的逻辑代码未生效

代码写出来,方便后续copy: (react) 父组件:

constructor(props: any, context: any) {
    super(props, context);
    this.state = {}
    //需要this指向组件实例
    this.handleMessage = this.handleMessage.bind(this);
}

componentDidMount() {
  window.addEventListener("message", this.handleMessage);
}

componentWillUnmount() {
  window.removeEventListener("message", this.handleMessage);
}

handleMessage(event: any) {
    if (event.data === "closePopup") {
        this.closePopup(); // 关闭弹窗的逻辑代码
    }
}

closePopup = () => {
    //代码逻辑   -- 关闭弹窗
    this.setState({visible: false})
}

子组件:

//倒计时为0,则向父级窗口发送消息 "closePopup"
if (this.state.count !== prevState.count && this.state.count === 0) {
  window.parent.postMessage("closePopup", "*");
}