iframe通信
<template><div id="iframe-container" class="data-container"><!-- 动态插入 iframe,无需静态标签 --></div>
</template><script>
import Cookies from 'js-cookie'export default {mounted() {const iframe = document.createElement('iframe');// 设置 iframe 样式(关键:去掉边框、占满容器)iframe.style.height = '100%';iframe.style.width = '100%';iframe.style.border = 'none'; // 移除 iframe 自身边框iframe.src = 'http://xxxxxx';document.getElementById('iframe-container').appendChild(iframe);// 在这里传参window.addEventListener('message', function(event) {if (event.data.type === 'READY') {console.log('收到 READY 消息');iframe.contentWindow.postMessage({type: 'LOGIN',userInfo: {username: Cookies.get('name'), password: Cookies.get('password'),captcha: true}}, '*'); }});}
}
</script><style scoped lang="scss">
.data-container {height: calc(100vh - 120px);width: 100%;margin: 0; // 清除外边距padding: 0; // 清除内边距
}
</style>
被嵌入的页面接受参数
window.parent.postMessage({type: 'READY'}, '*');window.addEventListener('message', (e) => {if (e.data.type === 'LOGIN') {console.log(e.data.userInfo) // 接受的参数}
});conso