[英]Is it a bad idea to use window.open and try to communicate between windows?
[英]Use 'window.open' and communicate with a child window
我的tomcat服务器中有两个页面。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="onBtnClick()">jump to child</button>
<script>
const msg = {
name:'index.html',
ifor:'I am your parent!'
};
function onBtnClick() {
const childWindow = window.open('./child.html');
childWindow.msg = msg
}
</script>
</body>
</html>
child.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="msg-panel"></div>
<script>
const msgPanel = document.querySelector('#msg-panel');
msgPanel.innerHTML = `<span>${msg.name}</span><br><span>${msg.ifor}</span>`
console.log(window.msg);
</script>
</body>
</html>
我想通过上述方式将一些消息(index.html中的msg对象)从index.html传递给child.html 。
当我单击index.html中的按钮以打开child.html时 ,有时可以在child.html中获得msg对象,但有时却不能。
因为您有时会收到该消息,有时却不尝试从index.html的脚本中放入代码:
document.addEventListener("DOMContentLoaded", function(event) {
//your code...
}
我认为您的HTML尚未加载,并且您单击按钮的速度过快。
将按钮设置为=“ =”
您在打开后设置消息。 有时计算机会更快,并且在显示之前不会通过消息。 使用超时在子级中显示消息,或者
const msgPanel = document.querySelector('#msg-panel');
msgPanel.innerHTML = `<span>${opener.msg.name}</span><br><span>${opener.msg.ifor}</span>`
console.log(window.msg);
尽管这已经解决了。 向孩子发送数据的另一种方法是localstorage
。 获取和设置非常容易,并且还支持IE11。
localStorage.setItem('msg', 'something important');
let msg = localStorage.getItem('msg');
这样,您还可以通过在localstorage change事件上设置事件侦听器来来回发送数据
window.addEventListener('storage', function(e) {
//do some cool stuff here
}
万一您想在父母与孩子之间进行更复杂的交流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.