JS 子父窗口互相操作取值赋值的方法可以用于在多个窗口或框架之间进行信息传递和交互。以下是几种常用的方法介绍和示例说明:
JS 子父窗口互相操作取值赋值的方法可以用于在多个窗口或框架之间进行信息传递和交互。以下是几种常用的方法介绍和示例说明:
1. 使用 window.opener 对象
window.opener 是指在当前窗口中打开的父窗口对象,可以通过该对象来实现对父窗口的操作。下面是一个例子,展示如何在子窗口中获取并修改父窗口的变量:
<!-- 父窗口 index.html -->
<!DOCTYPE html>
<html>
<head>
<title>父窗口</title>
<script>
var myVar = "Hello";
</script>
</head>
<body>
</body>
</html>
<!-- 子窗口 child.html -->
<!DOCTYPE html>
<html>
<head>
<title>子窗口</title>
<script>
window.onload = function() {
// 获取父窗口变量
alert(window.opener.myVar); // 输出 "Hello"
// 修改父窗口变量
window.opener.myVar = "World"; // 修改变量值
alert(window.opener.myVar); // 输出 "World"
}
</script>
</head>
<body>
</body>
</html>
注意,使用该方法需要注意跨域问题和安全性问题。
2. 使用 postMessage 方法
postMessage 方法可以用于在不同窗口和文档之间进行安全通信,可以实现双向通信(parent/child、sibling)或操作其他文档。以下是一个示例,在子窗口中向父窗口发送消息并实现两者之间的通信:
<!-- 父窗口 index.html -->
<!DOCTYPE html>
<html>
<head>
<title>父窗口</title>
<script>
function receiveMessage(event) {
var message = event.data;
console.log("Received message : " + message);
}
window.addEventListener("message", receiveMessage);
</script>
</head>
<body>
<h1>父窗口页面</h1>
<iframe src="child.html"></iframe>
</body>
</html>
<!-- 子窗口 child.html -->
<!DOCTYPE html>
<html>
<head>
<title>子窗口</title>
<script>
function sendMessage() {
var message = "Hello from child window!";
window.parent.postMessage(message, "*");
}
</script>
</head>
<body>
<h1>子窗口页面</h1>
<button onclick="sendMessage()">发送消息</button>
</body>
</html>
注意,postMessage 方法传递消息时需要指定传递给哪个窗口(targetWindow),并可以通过 Origin 属性实现通信安全性的保障。
以上是两种常用的 JS 子父窗口互相操作的方法介绍和示例说明。
本文标题为:JS子父窗口互相操作取值赋值的方法介绍


基础教程推荐
- JQ判断重置单选按钮radio为空 2022-10-30
- css3 实现元素弧线运动的示例代码 2023-12-27
- css锚点定位被顶部固定导航栏遮住的解决方案 2023-12-12
- html form表单基础入门案例讲解 2022-11-23
- vue+element模拟百度搜索(输入建议) 2023-10-08
- 在vue中解决 图片便利的问题 2023-10-08
- android WebView加载html5介绍 2023-12-20
- VUE3(二十)VUE自定义指令v-preventReClick,防止多次点击,重复请求 2023-10-08
- webpack学习笔记一:安装webpack、webpack-dev-server、内存加载js和html文件、loader处理非js文件 2023-10-27
- 用CSS动态控制文本属性 2022-10-16