zoukankan      html  css  js  c++  java
  • vue项目中使用iframe

    需求:
    将react项目内嵌到一个vue项目中,并且react项目中的请求需要携带vue项目中的cookie
     
    实现:
    使用iframe,用vue项目中在iframe的loaded事件中用postMessage传cookie,react项目中监听message事件
    此处在实践中发现:
    在react项目的app.js中,在componentDidMount钩子中监听message事件,获取到的都只是来自react项目本身的message,无法获取到来自vue项目中的message,最后采用了在组件外监听message
    还需要注意的一个问题是:
    在iframe嵌入的项目中监听message事件,获取到的message可能来自很多不同的origin,需要准确判断message来自哪里,需要根据origin做个条件筛选即可
     
    代码:
    vue项目中:
     
    <template>
    <div>
    <iframe id="template-iframe" ref="iframe" :src="src" @load="loaded" ></iframe>
    </div>
    </template>
     
    <script>
    export default {
    data () {
    return {
    iframeWin: {}
    }
    },
    computed: {
    src () {
    if (process.env.BASE_SYSTEM === 'devops_dev') {
    return 'http://0.0.0.0:8888/alerts_confirm'
    }
    return 'https://alert.ainnovation.com/alerts_confirm'
    }
    },
    methods: {
    loaded () {
    const cookie = document.cookie
    this.iframeWin.postMessage(cookie, this.src)
    }
    },
    mounted () {
    this.iframeWin = this.$refs.iframe.contentWindow
    }
    }
    </script>
     
    react项目中:
    function receiveMessage(event) {
    // console.log(event, event.data, '我接收到了')
    if (typeof event.data === 'string') {
    localStorage.setItem('cookie', event.data)
    }
    }
    window.addEventListener('message', receiveMessage, false)

  • 相关阅读:
    bower使用记录
    前端生成二维码
    删除顽固node_modules
    vue初体验:实现一个增删查改成绩单
    H5常用代码:适配方案5
    H5常用代码:适配方案4
    H5常用代码:适配方案3
    ARFA 教堂的第四次洗礼&斜率优化重学
    CSP考前总结&周二晚+周三晚模拟考总结&洛谷11月月赛 III Div.1总结
    T44253 绝美的挣扎 题解
  • 原文地址:https://www.cnblogs.com/fcybp/p/13603563.html
Copyright © 2011-2022 走看看