<template>
  <div>
    <!-- <button @click="openQrCode">打开扫码页面</button> -->
    <div v-if="receivedData">
      <h3>接收到的数据:</h3>
      <pre>{{ receivedData }}</pre>
    </div>
  </div>
</template>

<script>
export default {
  name: 'ScanPageCommunication',
  data() {
    return {
      bWindow: null,
      receivedData: null,
      checkCloseInterval: null
    };
  },
  methods: {
    openQrCode() {
      // 关闭已打开的窗口
      if (this.bWindow && !this.bWindow.closed) {
        this.bWindow.close();
      }

      // 打开扫码页面并保存引用
      this.bWindow = window.open('https://27.106.98.29:8443/testqrCode.html', '_blank');

      // 启动关闭检测
      this.checkCloseInterval = setInterval(() => {
        if (this.bWindow.closed) {
          clearInterval(this.checkCloseInterval);
          console.log('B页面已关闭');
        }
      }, 500);
    },

    handleMessage(event) {
      // 验证来源窗口
      if (this.bWindow && event.source === this.bWindow) {
        this.receivedData = event.data;
        console.log('收到来自B页面的数据:', event.data);
      }
      uni.showModal({
        title: '收到来自B页面的数据',
        content: event.data,
        duration: 2000,
      });
    }
  },
  mounted() {
    window.addEventListener('message', this.handleMessage);
  },
  beforeDestroy() {
    window.removeEventListener('message', this.handleMessage);
    if (this.checkCloseInterval) {
      clearInterval(this.checkCloseInterval);
    }
  }
};
</script>

<style scoped>
/* 样式按需自定义 */
</style>
