postMessage 收到消息类型 “webpackWarnings“

场景描述:

当A系统中的parent页面使用iframe内嵌C系统的child页面,并且在parent页面中通过postMessageg给child页面发送消息时,如果C系统中使用了webpack,则webpack也会给child页面发送消息 ,消息类型为webpackWarnings。那么如何使parent页面和child页面正确通信呢,主要分为以下两步。

1,parent页面要在iframe 加载完成之后,再给child页面发消息,同时约定好发送数据的格式

// parent.vue

<iframe

ref="iframeRef"

width="100%"

class="iframe-msg-content"

src="my-src"

frameborder="0"

></iframe>

<script setup>

import {onMounted, onUnmounted} from 'vue';

onMounted(()=>{

iframeRef.value.onload = () => {

// iframe 加载完成之后,获取iframe 内嵌子页面窗口

const childWindow = iframeRef.value.contentWindow;

const messageData = {

type: '约定的消息类型',

data: 要发送的数据,

};

// postMessage 发送字符串类型的数据才能被目标窗口接收

childWindow.postMessage(JSON.stringify(messageData), 'ip+端口');

};

window.addEventListener('message', handleMessage, false);

});

onUnmounted(() => {

window.removeEventListener('message', handleMessage, false);

});

</script>

// 先给一个默认的宽高

.iframe-msg-content{

width: 100%;

height: 400px

}

2,child页面监听message 事件获取来自parent页面发送的数据

// child.html最外层元素 .page-container

<div class="page-container" ref="pageContainer"></div>

<script setup lang="ts">

import {ref,reactive, onMounted, onUnmounted} from "vue";

const pageContainer = ref();

const state = reactive({

})

/**

* @description: 消息处理

* @return {*}

*/

const handleMessage = (event:MessageEvent) => {

// 因为webpack 发送的数据是对象类型,parent 页面发送的是经过JSON.stringify转换的字符串类型的

// 过滤来自webpack发送的possMessage 消息

if (Object.prototype.toString.call(event.data) === '[object String]') {

const message = JSON.parse(event.data);

if (message?.type === '约定好的数据type') {

// 处理来自parent 页面的数据

}

}

};

onMounted(()=>{

window.addEventListener('message', handleMessage);

})

onUnmounted(() => {

window.removeEventListener('message', handleMessage);

});

</script>

注意:

1,postMessage 发送字符串类型的数据才能被内嵌子页面接收。

2,通过类型过滤webpack发送的消息。

相关推荐
yangzhi_emo2 分钟前
ES6笔记2
开发语言·前端·javascript
yanlele18 分钟前
我用爬虫抓取了 25 年 5 月掘金热门面试文章
前端·javascript·面试
中微子1 小时前
React状态管理最佳实践
前端
烛阴2 小时前
void 0 的奥秘:解锁 JavaScript 中 undefined 的正确打开方式
前端·javascript
中微子2 小时前
JavaScript 事件与 React 合成事件完全指南:从入门到精通
前端
Hexene...2 小时前
【前端Vue】如何实现echarts图表根据父元素宽度自适应大小
前端·vue.js·echarts
初遇你时动了情2 小时前
腾讯地图 vue3 使用 封装 地图组件
javascript·vue.js·腾讯地图
dssxyz2 小时前
uniapp打包微信小程序主包过大问题_uniapp 微信小程序时主包太大和vendor.js过大
javascript·微信小程序·uni-app
华子w9089258592 小时前
基于 SpringBoot+VueJS 的农产品研究报告管理系统设计与实现
vue.js·spring boot·后端
天天扭码2 小时前
《很全面的前端面试题》——HTML篇
前端·面试·html