MENU

关于监听popup页面授权状态另外一个思路

October 1, 2023 • 已被 263 位童鞋围观过 • 代码分享,教程文章

今天在处理代码的时候,发现了这个问题,当用户在弹出的popup页面内完成授权,但是popup页面不能和主页面通讯。不停的查问题,才发popup页面 刚打开301跳转到google后,与主页面的通讯就断了,虽然授权完成后,再次回到当前域名 依旧不能通讯,找了很久的办法,最后才找到一个勉强能用的方法 那就是通过localStorage写入数据,监听localStorage数据变化 实现通信,但是这个毕竟是本地数据,存在被伪造的可能性,所以仅作为展示使用。不建议重要数据使用。

代码如下

const bind_Social = document.querySelectorAll('.bind-Social');
        bind_Social.forEach(btn => {
            btn.addEventListener('click', () => {
                const platform = btn.getAttribute('data-bind');
                const popup = openPopup(platform);
                window.addEventListener('storage', function(e) {
                    if(e.key === 'bind_Social') {
                        console.log(localStorage.getItem('bind_Social'))
                        if( localStorage.getItem('bind_Social') === "success") {
                            btn.innerHTML = 'Remove';
                            btn.className = 'button btn btn-link-danger remove-Social';
                            localStorage.setItem('bind_Social', 'bound');
                        }
                    }
                });

            });
        });

        function openPopup(platform) {
            const screenWidth = document.documentElement.clientWidth;
            const screenHeight = document.documentElement.clientHeight;
            const windowWidth = 600;
            const windowHeight = 800;
            const left = (screenWidth - windowWidth) / 2; 
            const top = (screenHeight - windowHeight) / 2;
            const options = `width=${windowWidth},height=${windowHeight},left=${left},top=${top}`; 
            const popup = window.open("/bind/" + platform, '', options);
            return popup; 
        }

可以实现 简单的监听状态。在获取到绑定成功的时候,给按钮加上新的样式。

授权完成的页面 JS 代码如下

<html>
<body>
    <script type="text/javascript">
        localStorage.setItem('bind_Social', 'success');
        setTimeout(() => {
            window.close();
        }, 500);
    </script>
</body>
</html>

在授权 callback 完成验证以后,写入bind_Social 数据,让主页面监听bind_Social字段变化,以完成通讯。