用JS中的window.name实现跨域数据传输

要求:    点击登录(OAuth2.0统一认证登录)跳转到 window.location.href = 'http://127.0.0.1:9000/oauth2/authorize?response_type=code&client_id=anchoremc-seed&scope=openid&redirect_uri=http://127.0.0.1:8000/signIn'; ,他会重定向到后端的登录页面http://127.0.0.1:9000/login.通过window.name把用户名和密码传递给,后端的登录页面http://127.0.0.1:9000/login做自动填充,怎么做?

前端代码

  1. 在登录表单的 handleCertificate 方法中,设置 window.name 属性。将用户名和密码以 JSON 格式存储在 window.name 中。

  2. 跳转到后端的登录页面

  3. const handleCertificate = async () => {
        const values = await form.validateFields().catch(error => {
            console.log(error);
        });
        const { remember, userName, password } = values as SignInForm;
    
        if (values && !code) {
            remember && setLocalStorage('signInfo', { remember, userName, password });
    
            // 将用户名和密码存储到 window.name
            window.name = JSON.stringify({ userName, password });
    
            // 跳转统一认证
            window.location.href =
                'http://127.0.0.1:9000/oauth2/authorize?response_type=code&client_id=anchoremc-seed&scope=openid&redirect_uri=http://127.0.0.1:8000/signIn';
        }
    };
    

    后端代码

    在后端的登录页面,您需要在页面加载时解析 window.name。以下是如何在后端获取 window.name 的示例:

  4. 在后端的登录页面 JavaScript 中,添加代码以读取 window.name
  5. <script type="text/javascript">
        document.addEventListener("DOMContentLoaded", function() {
            const userInfo = window.name ? JSON.parse(window.name) : null;
    
            if (userInfo) {
                // 自动填充用户名和密码
                document.getElementById('username').value = userInfo.userName;
                document.getElementById('password').value = userInfo.password;
    
                // 提交表单
                document.getElementById('form').submit();
            }
        });
    </script>
    

    注意事项

  6. 安全性:直接通过 window.name 传递用户名和密码可能会有安全隐患,确保在生产环境中采取其他措施(如 HTTPS 和 CSRF 防护)以保护用户凭证。
  7. 清理 window.name:在处理完数据后,最好清空 window.name 以避免后续访问时出现敏感信息。
    window.name = ''; // 清空
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值