iframe内嵌页面——跨域通讯
Posted wheatcatcher
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iframe内嵌页面——跨域通讯相关的知识,希望对你有一定的参考价值。
<template> <div class="act-form"> <iframe :src="src" ref="iframe" frameborder="no" align="middle" width="100%" height="600px" scrolling="auto" /> <el-button @click="sendMessage">向iframe发送信息</el-button> </div> </template> <script> export default data () return src: ‘‘, iframeWin: null, isLoaded: false , created () this.src = ‘http://odp.oa.com‘ //获取iframe var oIframe=document.getElementsByTagName(‘iframe‘)[0]; //获取iframe中的元素 var oText=oIframe.contentWindow.document.getElementById(‘navContent‘); //改变iframe中元素的属性 oIframe.contentWindow.document.getElementById(‘navContent‘).style.color=‘red‘; , mounted () // 在外部vue的window上添加postMessage的监听,并且绑定处理函数handleMessage window.addEventListener(‘message‘, this.handleMessage) this.iframeWin = this.$refs.iframe.contentWindow , methods: sendMessage () console.log(this.iframeWin, 1111111) this.iframeWin.postMessage( cmd: ‘getFormJson‘, params: , ‘*‘) , async handleMessage (event) // console.log(event, 222222) const data = event.data // console.log(data, 333333) switch (data.cmd) case ‘returnFormJson‘: break case ‘returnHeight‘: break , async enroll (data) console.log(‘4444444‘) </script>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>iframe Window</title> <style> body background-color: #D53C2F; color: white; </style> </head> <body> <h1>Hello there, i‘m an iframe</h1> <script> // 向父vue页面发送信息 window.parent.postMessage( cmd: ‘returnHeight‘, params: success: true, data: document.body.scrollHeight + ‘px‘ , ‘*‘) // 接受父页面发来的信息 window.addEventListener(‘message‘, function (event) var data = event.data switch (data.cmd) case ‘getFormJson‘: // 处理业务逻辑 break ) </script> </body> </html>
以上是关于iframe内嵌页面——跨域通讯的主要内容,如果未能解决你的问题,请参考以下文章