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>
2、postMessage方式通信
<template>
<div>
<button @click="handleClick">父按钮</button>
<iframe
style="display: block; width: 100%; height: 600px"
ref="iframeRef"
src="http://localhost:3000"
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?.postMessage(
{ data: '父向子发送消息' },
'*'
)
}
window.addEventListener('message', function (event) {
console.log('父窗口', event)
})
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.addEventListener("message", function(event) {
console.log("子窗口", event);
});
function handleClick() {
window.parent.postMessage({ data: "子向父发送消息" }, "*");
}
</script>
</body>
</html>