如何从window.open打开的新窗口中调用父页面index1.html的JS脚本
子窗口调用父窗口脚本的实现方案
你的两个页面都部署在https://localhost下,满足同源策略要求,可以用以下两种方案实现:
方案1:window.opener 直接调用(仅同源可用)
你通过window.open打开的子窗口会自动携带window.opener属性,指向打开它的父窗口(也就是index1.html)的window对象,你可以直接访问父窗口暴露在全局的方法:
- 先在index1.html中把要调用的方法挂载到全局作用域:
// index1.html 全局脚本 window.parentCustomFunc = function (params) { // 这里写你要执行的逻辑 console.log('父窗口方法被触发,收到参数:', params) }
- 在index2.html中直接调用即可:
// index2.html 脚本 // 调用前先判断父窗口是否还存在,避免报错 if (window.opener && !window.opener.closed) { window.opener.parentCustomFunc('来自子窗口的参数') }
方案2:postMessage 通信(同源/跨域通用)
如果后续有跨域调整的需求,推荐用更安全通用的postMessage方案,不需要直接访问对方的window属性,通过事件监听实现调用:
- 在index1.html中监听消息事件,处理子窗口的调用请求:
// index1.html 全局脚本 window.addEventListener('message', (event) => { // 安全校验,只处理可信来源的消息 if (event.origin !== 'https://localhost') return // 根据自定义的消息类型执行对应逻辑 if (event.data.action === 'callParentFunc') { const receiveParams = event.data.payload // 这里执行你要的业务逻辑 console.log('收到子窗口调用请求,参数:', receiveParams) // 可选:给子窗口返回执行结果 event.source.postMessage({ action: 'parentFuncResult', data: '执行完成' }, event.origin) } })
- 在index2.html中发送消息触发父窗口逻辑,也可以监听返回结果:
// index2.html 脚本 if (window.opener && !window.opener.closed) { // 向父窗口发送调用请求 window.opener.postMessage({ action: 'callParentFunc', payload: '来自子窗口的参数' }, 'https://localhost') } // 可选:监听父窗口的返回结果 window.addEventListener('message', (event) => { if (event.origin !== 'https://localhost') return if (event.data.action === 'parentFuncResult') { console.log('父窗口返回结果:', event.data.data) } })
注意事项
- 两种方案都需要先判断
window.opener && !window.opener.closed,避免父窗口关闭后调用报错 - 方案1仅适用于同源场景,写法更简单;方案2不受同源限制,安全性更高,更推荐使用
内容的提问来源于stack exchange,提问作者Ziregbe Otee
相关产品推荐
相关产品推荐

