接收iframe消息后跳转本地页面的父页面代码实现求助
实现父页面接收iframe消息后跳转本地页面
父页面核心代码
在父页面的脚本中添加消息监听与跳转逻辑,必须验证消息来源以避免安全风险:
window.addEventListener('message', (event) => { // 替换为你的iframe实际域名/地址,仅信任该来源的消息 const trustedOrigin = 'https://your-iframe-domain.com'; if (event.origin !== trustedOrigin) return; // 匹配iframe发送的提交成功标识(和你iframe端发送的内容对应) if (event.data === 'form-submit-success') { // 跳转到目标本地页面,替换为你的实际路径 window.location.href = '/success-local-page.html'; // 若不想保留当前页面历史记录,可改用: // window.location.replace('/success-local-page.html'); } });
关键说明
- 来源验证:永远不要省略
event.origin的校验,否则恶意网站可通过iframe向你的页面发送消息触发跳转,造成安全问题。 - 消息匹配:
event.data的判断逻辑要和你iframe中发送的内容一致——如果你在iframe里发送的是对象(比如{ type: 'form', status: 'success' }),父页面就对应判断event.data.type === 'form' && event.data.status === 'success'。 - 本地路径写法:如果目标页面和父页面同目录,直接写
'success.html';如果是根目录下的页面,写'/success.html';子目录则写'/subdir/success.html'。
iframe端配合代码(供参考)
如果你需要确认iframe端的发送逻辑是否正确,这里给出示例(你已掌握可忽略):
// 监听表单提交 document.getElementById('your-form-id').addEventListener('submit', async (e) => { e.preventDefault(); // 执行表单提交逻辑(如AJAX提交到后端) const submitResult = await fetch('/api/submit-form', { method: 'POST', body: new FormData(e.target) }); if (submitResult.ok) { // 发送消息给父页面,建议指定父页面域名而非* window.parent.postMessage('form-submit-success', 'https://your-parent-domain.com'); } });
内容的提问来源于stack exchange,提问作者Apóstoles EquiposInn
相关产品推荐
相关产品推荐

