window.open打开子窗口回调父窗口函数

本文介绍了在前端项目中,如何利用window.open打开子窗口,并在子窗口操作完成后通过postMessage方法回调父窗口函数,关闭子窗口并提示信息。示例代码展示了如何在jsp页面中实现这一功能,包括parent.html和child.html两个页面的交互。在实际应用中,注意避免消息监听器被多次触发的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

window.open打开子窗口回调父窗口函数

需求

最新在工作中,遇到一个需求。老项目的前端页面使用的是jsp技术,产品要求点击按钮弹出一个弹窗进行操作,操作成功要关闭子页面,还要提示成功信息。
本来想使用ajax的请求方式传json数据的,但是表单中包含了文件和数据,在加上后台的接收方法但是有现成的公用方法。于是就使用了window.open打开窗口。

解决方法

在子窗口跳转到父窗口的时候进行关闭子窗口,回调父窗口函数。

    <script>
        // 如果父窗口存在,就关闭这个窗口,给父函数发消息
        if(window.parent.opener != null){
            window.close()
            window.parent.opener.postMessage('我回来了', '*');
        }

        window.addEventListener('message', function (data) {
            alert(data.data)
        })
    </script>

完整测试代码

parent.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="btn">打开子窗口</button>
    <script>
        console.log('====================')
        if(window.parent.opener != null){
            window.close()
            window.parent.opener.postMessage('我回来了', '*');
        }
        console.log('====================')



        var btn = document.getElementById('btn')
        btn.addEventListener('click', function () {
            window.open('child.html', '','width=600,height=300')
        })

        window.addEventListener('message', function (data) {
            alert(data.data)
            console.log(data.data);
        })
    </script>
</body>

</html>

child.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- <button id="btn">给父窗口发消息</button> -->
    <a href="parent.html">回到父窗口</a>
    <script>

        var btn = document.getElementById('btn')
        btn.addEventListener('click', function () {
            window.parent.opener.postMessage('我回来了', '*');
            window.close()
        })
    </script>
</body>
</html>

补充

今天实测发现监听器会被反复调用,后面找到解方法

window.onmessage=function(e) {
 // code
}




最后,感谢前端大佬gjj的技术支持。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值