feat: iframe页面是否同源的事件监听(协议,域名,端口号完全一致为同源)

master
LCJ-MinYa 11 months ago
parent 295c573e0f
commit c91cdeaa92

@ -0,0 +1,33 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
<title>iframe嵌入页面</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
background: #999;
}
</style>
</head>
<body>
<div>
<h3>我是iframe嵌入的子页面</h3>
<button id="btn">点击我</button>
</div>
</body>
</html>
<script>
onload = function () {
document.getElementById('btn').addEventListener('click', function () {
alert('子页面:你点击了按钮');
});
};
</script>

@ -48,6 +48,10 @@ const titleArr = [
key: 'dynamicNodeEvent',
title: '动态html加载的事件监听',
},
{
key: 'iframeEvent',
title: 'iframe页面的事件监听',
},
];
// @/views/demo/**/*.vue

@ -0,0 +1,68 @@
<template>
<div class="iframe-event">
<iframe
id="iframe1"
src="/demoHtml/iframe.html"
frameborder="0"
width="300"
height="300"
/>
<!-- 下面这个地址是使用的vscode启动的本地服务每次需要手动修改和修改该地址这里是为了模拟跨域情况 --->
<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>

@ -38,7 +38,8 @@ export default ({ mode }: ConfigEnv): UserConfigExport => {
rollupOptions: {
input: {
index: pathResolve('./index.html', import.meta.url),
demoHtml: pathResolve('./demoHtml/layout.html', import.meta.url),
layoutHtml: pathResolve('./demoHtml/layout.html', import.meta.url),
iframeHtml: pathResolve('./demoHtml/iframe.html', import.meta.url),
},
// 静态资源分类打包
output: {

Loading…
Cancel
Save