使用通義千問提問后得到一個很好的示例。
需求是2個項目需要使用同一個面包屑進行跳轉,其中一個是iframe所在的項目,另一個需要通過地址訪問。通過?window.parent.postMessage ,幫助 <iframe>
?內嵌入的子頁面和其父頁面之間進行跨域通信。
【子頁面】
// 子組件 (假設這是在iframe中的Vue應用)
new Vue({el: '#app',methods: {sendMessageToParent(url) {// 向父頁面發送消息,包括目標URLwindow.parent.postMessage({ action: 'changeIframeSrc', url }, '*');}},template: `<button @click="sendMessageToParent('https://example.com/new-content')">Load New Content</button>`
});
【父頁面】
<!-- 父頁面 HTML -->
<div id="app"><iframe ref="myIframe" :src="currentUrl" width="600" height="400"></iframe>
</div>
// 父頁面 Vue 實例
new Vue({el: '#app',data() {return {currentUrl: 'https://example.com/initial-content' // 初始URL};},mounted() {// 監聽來自子組件的消息window.addEventListener('message', this.handleMessage);},beforeDestroy() {// 移除事件監聽器以防止內存泄漏window.removeEventListener('message', this.handleMessage);},methods: {handleMessage(event) {const { data } = event;// 安全檢查:驗證消息來源和預期動作if (data.action === 'changeIframeSrc' && typeof data.url === 'string') {// 更新 iframe 的 src 屬性this.currentUrl = data.url;}}}
});
請注意,在實際應用中,你不應該使用 '*'
作為 postMessage 的目標源參數,因為它允許消息被發送到任何域,這可能會導致安全問題。你應該指定一個明確的源,如 'https://your-iframe-domain.com'
,以便只接受來自特定域的消息。同樣地,在父頁面接收消息時,你也應該檢查 event.origin
來確保消息確實來自預期的域。
【資料參考】
通義tongyi.ai_你的全能AI助手-通義千問