消息通道上的错误:"No function was found that matched the signature provided"



当我使用 MessageChannel 并触发sendMsg事件时,出现错误:TypeError: Failed to execute 'postMessage' on 'MessagePort': No function was found that matched the signature provided .

我对此知之甚少,有人可以给出一些建议吗?

A.vue

<template>
  <div class="block">
    <iframe src="/messaging/channel-messaging/b" />
    <iframe src="/messaging/channel-messaging/c" />
  </div>
</template>
<script>
export default {
  mounted() {
    window.addEventListener('message', e => {
      if (e.ports.length !== 0) {
        window.frames[1].postMessage('initPort', '*', e.ports)
      }
    })
  }
}
</script>

B.vue

<template>
  <div class="block">
    <p>
      <input type="text" v-model="msg">
      <button @click="sendMsg">send</button>
    </p>
    <p>c say:{{ receiveMsg || 'nothing' }}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      msg: '',
      receiveMsg: '',
      port: ''
    }
  },
  mounted() {
    const mc = new MessageChannel()
    this.port = mc.port2
    window.parent.postMessage('B has loaded', '*', [mc.port1])
    mc.port2.onmessage = e => {
      this.receiveMsg = e.data
    }
  },
  methods: {
    sendMsg() {
      if (this.port) {
        this.port.postMessage(this.msg, '*')
      }
    }
  }
}
</script>

c.vue

<template>
  <div class="block">
    <p>
      <input type="text" v-model="msg">
      <button @click="sendMsg">send</button>
    </p>
    <p>b say:{{ receiveMsg || 'nothing' }}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      msg: '',
      receiveMsg: '',
      port: ''
    }
  },
  mounted() {
    window.parent.postMessage('C has loaded', '*')
    window.addEventListener('message', e => {
      if (e.data === 'initPort') {
        this.port = e.ports[0]
        this.port.onmessage = e => {
          this.receiveMsg = e.data
        }
      }
    })
  },
  methods: {
    sendMsg() {
      if (this.port) {
        this.port.postMessage(this.msg, '*')
      }
    }
  }
}
</script>

与 Window.postMessage 不同,MessageChannel.port.postMessage 没有origin参数,因为这个 MessageChannel 只有一个你已经信任的通讯员。

因此,port.postMessage(msg, "*") 中的"*"实际上被传递为应该是 transferList,但它不可转移,因此出现了错误。

const channel = new MessageChannel();
channel.port1.postMessage('foo', '*'); // throws

只需将其删除,您就会没事的。

相关内容

最新更新