• 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)

  • 相关阅读:
    怎样解决:未找到路径“……”的控制器或该控制器未实现 IController?
    错误:org.springframework.jdbc.support.SQLErrorCodesFactory
    springbean的生命周期
    注解到处excel
    nio读取文件,输出文件
    AtomicReference
    唯一id
    hashmap1.7的死锁模拟
    数组模拟stack
    环形队列
  • 原文地址:https://www.cnblogs.com/fcybp/p/13603563.html
Copyright © 2020-2023  润新知