目录
1、contentWindow方式通信
- 声明文件
declare global {
interface Window {
childDefineFunction: (message: string) => void
fatherDefineFunction: (message: string) => void
}
}
export {}
- 父窗口
<template>
<div>
<button @click="handleClick">父按钮</button>
<iframe
style="display: block; width: 100%; height: 600px"
ref="iframeRef"
src="/child.html"
frameborder="0"
></iframe>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
export default defineComponent({
setup() {
const iframeRef = ref<HTMLIFrameElement>()
const handleClick = () => {
// 需在同一个域
iframeRef.value?.contentWindow?.childDefineFunction('父向子发送消息')
}
window.fatherDefineFunction = (message) => {
console.log(message)
}
return {
iframeRef,
handleClick
}
}
})
</script>
<style lang="scss" scoped></style>
- 子窗口
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>子窗口</title>
<style>
html, body {
height: 100%;
}
body {
margin: 0;
background: #cccccc;
}
</style>
</head>
<body>
<button onclick="handleClick()">子按钮</button>
<script>
window.childDefineFunction = (message) => {
console.log(message);
};
function handleClick() {
window.parent.fatherDefineFunction("子向父发送消息");
}
</script>
</body>
</html>