postMessage跨域失败

http://localhost:8081中用iframe嵌套http://localhost:8080

<template>
    <div class="system-content-wrapper active1" :style="!hideSwipe?'width: calc(100% - 25px);':null">
        <iframe class="iframe-wrapper" ref="iframe" id="iframe" name="iframe" src="http://localhost:8080"></iframe>
    </div>
</template>

http://localhost:8081发送数据

postMessage() {
    var obj = window.frames['iframe'];
    obj.postMessage("123", "http://localhost:8080")
}

http://localhost:8080接受数据

window.addEventListener('message', function (event) {
  console.log(event.origin);
  // if (event.origin != 'http://localhost:8081') return;
  console.log('received response:  ', event.data);
}, true);

控制台报错

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:8080') does not match the recipient window's origin ('http://localhost:8081').

response data未定义

图片描述


求解,是我用法不对还是postMessage不支持跨域?

阅读 11.7k
4 个回答
obj.postMessage("123", "*")

看看

obj.postMessage

obj是接收方的引用

top.postMessage

data是undefined解决了么?

新手上路,请多包涵

data是undefined解决了么?

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题