MessageChannel上的错误:“找不到与提供的签名匹配的功能”

时间:2019-04-04 08:22:46

标签: javascript

当我使用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>

1 个答案:

答案 0 :(得分:0)

与Window.postMessage不同,MessageChannel.port.postMessage没有origin参数,因为您确实信任此MessageChannel的其他对应者。

因此"*"中的port.postMessage(msg, "*")实际上应该作为 transferList 传递,但不是transferable,因此是错误。

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

只需将其删除,就可以了。