<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>
原文地址:https://www.cnblogs.com/wheatCatcher/p/11165514.html
时间: 2024-11-05 13:45:20