前端如何使得兩個項目之間通信,window.open + postMessage

一、背景

由於公司內部需求不斷加大,一個項目無法滿足,多個項目直接需滿足互相通信,則需要解決跨域傳遞消息的問題

 

二、兩個項目之間如何通信,如何解決解決跨域傳遞消息

1. A.html ( https://www.a.com )

<div @click="goDetail('參數id')">傳遞信息</div>
<script>
getMessage()
let timeOfmsg = null
function getMessage() {
    // 接收消息
    window.addEventListener('message', (e) => {
        console.log('no 接收到數據')
        if (e.data === 'getMsg') {
            // @ts-ignore
            console.log('接收到數據')
            clearInterval(timeOfmsg)
        }
    })
}

// 跳轉到畫板編輯頁面
function goDetail(id) {
    let url = 'https://www.b.com'
    // 打開畫布
    const targetWindow = window.open(`${url}?id=${id}`, '_blank')
    // 發送消息
    timeOfmsg.value = setInterval(() => {
        console.log('已發送消息')
        targetWindow.postMessage(localStorage.getItem('TOKEN'), url)
    }, 1000)
}
</script>

  

2. B.html ( https://www.b.com )

<script>  
window.addEventListener(
    'message',
    (event) => {
    // 判斷接收信息的來源是否來自於 https://www.a.com if (event.origin != 'https://www.a.com') return; // 將接收到的數據存儲到本地 localStorage.setItem('TOKEN', event.data); // 返回消息,告知已收到數據 event.source.postMessage('getMsg', event.origin); }, false ); </script>

  

 三、坑點

1. onload (失敗)

window.open('xxx').onload = () => {
	window.postMessage(message, targetOrigin, [transfer]);
}

2. setTimeout (失敗,由於B網站不一定什麼時候加載完成)

setTimeout(() => window.postMessage(this.userSession, targetUrl), 3000);

3. setInterval(成功,A網站定時器不斷髮送消息,當B網站接收到信息後,向A網站回覆消息爲已收到,關閉A網站的定時器)

let timeOfmsg = setInterval(() => {
      winopen.postMessage(this.userSession, targetUrl);
}, 3000);

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章