vue中iframe标签跨域通信——父子页面之间传值(解决子页面收不到父页面的值或子页面收到的数据为undefined的问题)
    		       		warning:
    		            这篇文章距离上次修改已过444天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue中,如果你需要在父页面和嵌入的iframe之间进行通信,你可以使用window.postMessage()方法。以下是一个简单的例子:
父页面(Parent.vue):
<template>
  <div>
    <iframe id="my-iframe" src="http://your-iframe-domain.com/child.html"></iframe>
    <button @click="sendMessage">Send Message to Iframe</button>
  </div>
</template>
 
<script>
export default {
  methods: {
    sendMessage() {
      const iframe = document.getElementById('my-iframe');
      iframe.contentWindow.postMessage('Hello, I am from the parent!', 'http://your-iframe-domain.com');
    }
  }
}
</script>子页面(Child.html):
<script>
  window.addEventListener('message', function(event) {
    if (event.origin !== "http://your-parent-domain.com") return;
    console.log(event.data); // 输出: Hello, I am from the parent!
  }, false);
</script>确保替换http://your-iframe-domain.com/child.html和http://your-parent-domain.com为实际的域名。
在父页面中,你可以通过获取iframe的contentWindow然后调用postMessage方法发送消息。在子页面中,你需要监听message事件来接收从父页面发送过来的消息。
请注意,window.postMessage()方法可以跨域通信,但是发送方和接收方的协议、端口和主机名必须匹配,否则消息事件不会被触发。
评论已关闭