对于iframe子页面与父页面通信,需要注意同域或不同域等情况。
对于iframe子页面与父页面通信,需要注意同域或不同域等情况。
同域下的js通信
当子页面和父页面在同一个域名下时,js通信可以通过window.parent对象来进行。以下是一个简单的示例。
父页面代码:
<!DOCTYPE html>
<html>
<head>
<title>父页面</title>
</head>
<body>
<h1>我是父页面</h1>
<div id="content"></div>
<script>
window.onload = function() {
var iframe = document.createElement('iframe');
iframe.src = 'iframe.html';
document.body.appendChild(iframe);
window.addEventListener('message', function(e) {
console.log('父页面接收到:' + e.data);
document.getElementById('content').innerHTML = e.data;
});
}
</script>
</body>
</html>
子页面代码:
<!DOCTYPE html>
<html>
<head>
<title>子页面</title>
</head>
<body>
<h1>我是子页面</h1>
<button onclick="sendMsg()">发送消息到父页面</button>
<script>
function sendMsg() {
window.parent.postMessage('这是子页面发来的消息', '*');
}
</script>
</body>
</html>
子页面中通过window.parent.postMessage方法发送消息到父页面。父页面中通过window.addEventListener方法监听message事件,并在事件处理程序中接收子页面的消息进行处理,此处将子页面传来的消息插入到页面中的content的div元素中。
不同域下的js通信
当子页面和父页面的域名不同时,js通信需要通过跨域postMessage方式来实现。以下是一个简单的示例。
父页面代码:
<!DOCTYPE html>
<html>
<head>
<title>父页面</title>
</head>
<body>
<h1>我是父页面</h1>
<div id="content"></div>
<script>
window.onload = function() {
var iframe = document.createElement('iframe');
iframe.src = 'http://127.0.0.1:8888/iframe.html';
document.body.appendChild(iframe);
window.addEventListener('message', function(e) {
console.log('父页面接收到:' + e.data);
document.getElementById('content').innerHTML = e.data;
});
}
</script>
</body>
</html>
子页面代码:
<!DOCTYPE html>
<html>
<head>
<title>子页面</title>
</head>
<body>
<h1>我是子页面</h1>
<button onclick="sendMsg()">发送消息到父页面</button>
<script>
function sendMsg() {
window.parent.postMessage('这是子页面发来的消息', 'http://127.0.0.1:8888');
}
</script>
</body>
</html>
子页面中同样是通过window.parent.postMessage方法发送消息到父页面,只不过这里需要指定父页面的域名。父页面中同样在iframe中嵌入子页面,然后通过window.addEventListener方法监听message事件,在事件处理程序中接收子页面的消息进行处理。
需要注意的是,父页面中的iframe src属性需要指定完整的子页面地址,例如:http://127.0.0.1:8888/iframe.html;而子页面中的发送消息时指定的域名也需要指定完整,例如:http://127.0.0.1:8888。
以上是iframe子页面与父页面在同域或不同域下的js通信的完整攻略。
本文标题为:iframe子页面与父页面在同域或不同域下的js通信
基础教程推荐
- js禁止页面刷新与后退的方法 2024-01-08
- 关于文字内容过长,导致文本内容超出html 标签宽度的解决方法之自动换行 2023-10-28
- Ajax实现动态加载数据 2023-02-01
- 浅析canvas元素的html尺寸和css尺寸对元素视觉的影响 2024-04-26
- this[] 指的是什么内容 讨论 2023-11-30
- CSS3的几个标签速记(推荐) 2024-04-07
- vue离线环境如何安装脚手架vue-cli 2025-01-19
- 基于Vue制作组织架构树组件 2024-04-08
- 浅谈Vue2和Vue3的数据响应 2023-10-08
- JS前端广告拦截实现原理解析 2024-04-22
