在JavaScript中,父窗体可以通过多种方式向子窗体传递数据或赋值。以下是一些常见的方法:
window.postMessage
:安全地在不同源的窗口之间传递消息。// 父窗体
const childWindow = window.open('child.html?id=123&name=John');
// 子窗体 (child.html)
window.onload = function() {
const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('id');
const name = urlParams.get('name');
console.log(`ID: ${id}, Name: ${name}`);
};
window.postMessage
// 父窗体
const childWindow = window.open('child.html');
childWindow.onload = function() {
childWindow.postMessage({ id: 123, name: 'John' }, '*');
};
// 子窗体 (child.html)
window.addEventListener('message', function(event) {
if (event.origin !== 'http://example.com') return; // 安全检查
console.log('Received data:', event.data);
});
// 父窗体
const childWindow = window.open('child.html');
childWindow.myData = { id: 123, name: 'John' };
// 子窗体 (child.html)
console.log(window.myData); // { id: 123, name: 'John' }
原因:浏览器的同源策略限制了不同源之间的脚本交互。
解决方法:使用window.postMessage
方法,并确保在接收消息时进行源的安全检查。
原因:可能是由于URL参数编码不正确或postMessage
的源检查不严格。
解决方法:确保所有数据都正确编码,并且在接收消息时严格验证消息来源。
通过上述方法和注意事项,可以有效地在父窗体和子窗体之间传递数据。选择合适的方法取决于具体的应用场景和需求。
领取专属 10元无门槛券
手把手带您无忧上云