Window postMessage() 方法 | 菜鸟教程
父窗口代码:
<template><iframe id="iframe" ref="iframe" :src="uri" frameborder="0" scrolling="auto"></iframe>
</template><script>
export default {data() {return {drawerLoading:false, uri:"http://10.54.49.149:80/iframe/itsm",};},created() {//给子窗口发送参数this.postMessage()//接收子窗口传递的参数this.getMessage(); },mounted() {},methods: {//给子窗口发送信息postMessage(row) {/*** iframe加载子窗口完成时通过postMessage传递数据*/this.drawerLoading = true;this.$nextTick(() => {let mapFrame = this.$refs["iframe"];mapFrame.onload = () => {this.drawerLoading = false;let iframeWin = mapFrame.contentWindow;iframeWin.postMessage({//给子窗口传递的参数code: "itsm",params: {documentId: "",modelId: "3",instanceSelectAbled: true,},},this.uri //给哪个域名下的子窗口发送【可改为 *,即通配】);};});},//接收子窗口传递的参数getMessage() {window.onmessage = this.handleMessage;// window.addEventListener("message", this.handleMessage);},handleMessage(event) {let data = event.data;if (data && data.code) {if (data.params.method === "cancel") {//取消} else {//确认、删除if (data.params.res.code !== "S1A00000") {return this.$message.error(data.params.res.msg);}this.$message({message: data.params.res.msg,type: "success",});}} else {}},},
};
</script>
<style >
#iframe {width: 100%;height: 100%;overflow: auto;
}
</style>
子窗口代码示例
<template><div class="iframeRouter"><el-buttontype="primary"@click="toParentWindow({ code: 'cmdb', params: { method: 'cancel' } })">给父窗口发送信息</el-button></div>
</template>
<script>
export default {name: "",components: {},data() {return {//赋值:父窗口传来的参数parentConfig: {origin: "",code: "",params: {},},};},created() {//接收父窗口传过来的参数this.getMessage();},mounted() {},methods: {//给父窗口发送信息toParentWindow(params) {window.parent.postMessage({code: "cmdb",params,},"*");},// 接收父窗口传递的信息getMessage() {window.onmessage = this.handleMessage;},handleMessage(event) {let data = event.data;if (data && data.code) {let passOrigins = ["http://localhost",window.SITE_CONFIG["sysConfig"].itsm.production, // itsm的域名 生产环境window.SITE_CONFIG["sysConfig"].itsm.test, // itsm的域名 测试环境];let origin = passOrigins.find((item) => {return event.origin.indexOf(item) !== -1;});if (!origin) {this.$router.replace({ name: "login" });return this.$message.warning("当前域名不可加载此页面");}this.parentConfig = {origin: origin,code: data.code,params: data.params,};if (data.code === "itsm") {//本页面的一系列操作this.initPage();}} else {}},initPage() {// 一系列的操作},},
};
</script>
<style lang="scss">
</style>