【发布时间】:2020-08-14 19:00:57
【问题描述】:
下午好,
我想将 localStorage 设置为另一个域。我使用了 postMessage 功能。 这是父页面:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
var childwin;
const childname = "popup";
function openChild() {
childwin = window.open('Page2.html', childname, 'height=300px, width=500px');
}
function sendMessage(){
let msg={pName : "Bob", pAge: "35"};
// In production, DO NOT use '*', use toe target domain
childwin.postMessage(msg,'*')// childwin is the targetWindow
childwin.focus();
}
</script>
</head>
<body>
<form>
<fieldset>
<input type='button' id='btnopen' value='Open child' onclick='openChild();' />
<input type='button' id='btnSendMsg' value='Send Message' onclick='sendMessage();' />
</fieldset>
</form>
</body>
</html>
这里是孩子们:
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script>
// Allow window to listen for a postMessage
window.addEventListener("message", (event)=>{
// Normally you would check event.origin
// To verify the targetOrigin matches
// this window's domain
let txt=document.querySelector('#txtMsg');
localStorage.setItem("age", event.data.pAge);
// event.data contains the message sent
txt.value=`Name is ${event.data.pName} Age is ${event.data.pAge}` ;
});
</script>
</head>
<body>
<form>
<h1>Recipient of postMessage</h1>
<fieldset>
<input type='text' id='txtMsg' />
</fieldset>
</form>
</body>
</html>
这很好用,但我们需要 2 个按钮。一个打开页面,另一个发布消息。
如果我想让这两个方法 openChild();postMessage() 在同一个按钮中,它不起作用。
我认为是因为我们调用 postMessage() 时 page2.html 没有完全加载。
我们该怎么做?
最好的问候。
克里斯托夫。
【问题讨论】:
标签: javascript html cross-domain postmessage