vue项目嵌套iframe,发送、接收数据

<template>
    <div class="home">
        <iframe src="http://127.0.0.1:8888/index.html" class="mapFrame" ref="mapFrame"></iframe>
    </div>
</template>
 
<script>
    export default {
        mounted() {
            let mapFrame = this.$refs['mapFrame']
            if (mapFrame.attachEvent){  //兼容浏览器判断
                mapFrame.attachEvent("onload", function(){ 
                    let iframeWin = mapFrame.contentWindow
                    iframeWin.postMessage({
                        method: 'getBaseInfo',
                        data:'我是vuex state的数据'
                    },'*')
                })
            } else { 
                mapFrame.onload = function(){ 
                    let iframeWin = mapFrame.contentWindow
                    iframeWin.postMessage({
                        method: 'getBaseInfo',
                        data:'我是vuex state的数据'
                    },'*')
                } 
            }
            
        }
    }
</script>
 
<style scoped lang="stylus">
.home {
    .mapFrame {
        height: 300px;
        width: 500px;
    }
}
</style>



    子页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>iframe嵌套网页测试</title>
</head>
<body>

    <script>
        window.addEventListener('message',function(e){
            console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
            console.log(e.origin,e.data)
        })  
        // window.postMessage({
        //     method:'localtest',
        //     data:'ddddddddddddddddddddddddddddd'
        // },'*')
    </script>
</body>
</html>
发布了35 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_39024950/article/details/90317738