iframe

放到uniapp的static/web/viewer.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>iframe嵌入的页面</title>
</head>

<body>
    <button onclick="iframeSendMsg()">iframe向Vue传消息</button>
    <script>
        // iframe获取Vue传递过来的信息
        window.addEventListener("message", getVueMsg);
        function getVueMsg(event) {
            const res = event.data;
            if (res.cmd == 'myVue') {
                console.log('iframe获取Vue传递过来的信息', res)
            }
        };

        // iframe向vue传递信息
        function iframeSendMsg() {
            window.parent.postMessage({
                cmd: 'myIframe',
                params: {
                    info: 'iframe向Vue传递的消息',
                }
            }, '*');
        };
                //用于vue调用 
        function triggerByVue(msg) {
            console.log(msg)
        }
    </script>
</body>
</html>

vue

<template>
    <div class="wrap">
        <iframe ref="iframe" :src="`${viewerUrl}`" width="100%" height="50%" frameborder="0">
        </iframe>
        <button @click="vueSendMsg">vue向iframe传递信息</button>
        <button @click="iframeMethods">调用iframe中的方法</button>
    </div>
</template>

<script>
    export default {
        data() {
            return {
            
                viewerUrl: '../../static/web/viewer.html',
            };
        },
        methods: {
            // vue获取iframe传递过来的信息
            getiframeMsg(event) {
                const res = event.data;
                console.log(event)
                if (res.cmd == 'myIframe') {
                    console.log(res)
                }
            },
            // vue向iframe传递信息
            vueSendMsg() {
                const iframeWindow = this.$refs.iframe.contentWindow;
                iframeWindow.postMessage({
                    cmd: 'myVue',
                    params: {
                        info: 'Vue向iframe传递的消息',
                    }
                }, '*')
            },
            // 触发iframe中的方法
            iframeMethods() {
                this.$refs.iframe.contentWindow.triggerByVue('通过Vue触发iframe中的方法');
            },
        },
        mounted() {
            window.addEventListener('message', this.getiframeMsg)
        },
    };
</script>


<style lang="scss" scoped>
    .wrap {
        width: 100%;
        height: 500px;
    }
</style>

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐