You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 lines
1.9 KiB
Vue

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<template>
<div class="iframe-event">
<!-- 同源iframe嵌入页面 -->
<iframe
id="iframe1"
src="/demoHtml/iframe.html"
frameborder="0"
width="300"
height="300"
/>
<!-- 下面这个地址是使用的vscode启动的本地服务每次需要手动修改和修改该地址这里是为了模拟跨域情况 --->
<!-- 跨域iframe嵌入页面 -->
<iframe
id="iframe2"
src="http://localhost:52330/demoHtml/iframe.html"
frameborder="0"
width="300"
height="300"
/>
</div>
</template>
<script setup>
import { onMounted } from 'vue';
const getChildDocument = (iframe) => {
let childDocument = null;
try {
childDocument = iframe.contentDocument || iframe.contentWindow.document;
} catch (error) {
console.log('无法访问跨域 iframe 的内容:', error);
}
return childDocument;
};
const initIframe = (idName) => {
const iframe = document.getElementById(idName);
// 确保子页面加载完成后再访问其 DOM
iframe.onload = function () {
const childDocument = getChildDocument(iframe);
if (!childDocument) {
return;
}
// 访问子页面的 DOM
const childElement = childDocument.getElementById('btn');
childElement.innerHTML = '我是同源,点击我'; // 修改子页面元素的文本
childElement.style.color = 'red'; // 修改子页面元素的样式
// 添加事件监听
childElement.addEventListener('click', function () {
alert('父页面:子页面按钮被点击了!');
});
};
};
onMounted(() => {
initIframe('iframe1');
initIframe('iframe2');
});
</script>
<style scoped>
.iframe-event {
display: flex;
justify-content: space-around;
align-items: center;
height: 100%;
}
</style>