从弹出窗口设置localStorage

问题描述 投票:0回答:1

我有一个弹出窗口,用于处理用户的身份验证。我想在localStorage中设置用户的organization_id,以便我可以访问它。以下是我执行失败结果的步骤。

  1. 单击登录。这会触发弹出窗口
  2. 输入电子邮件和密码。成功验证后,弹出窗口将关闭。
  3. 检查localStorage。 organization_id不存在任何属性

以下是我为获得成功而采取的以下步骤。

  1. 暂时修改代码以防止关闭弹出窗口。
  2. 单击登录。这会触发弹出窗口。
  3. 输入电子邮件和密码。弹出窗口熬夜。
  4. 检查localStorage并发现实际上存在正确设置的organization_id。
  5. 还原代码,以便弹出窗口再次关闭。
  6. 单击登录。触发弹出窗口。
  7. 输入电子邮件和密码。弹出窗口关闭。
  8. 检查localStorage。现在有一个organization_id。

所有更改后,我正在进行硬重置并清空缓存。

什么可以解释这种奇怪的行为?为什么在弹出窗口中检查它会导致它工作?

handleAuthentication () {
this.auth0.parseHash({hash: window.location.hash}, (err, authResult) => {
  if (authResult && authResult.accessToken && authResult.idToken) {
    this.setSession(authResult);
    window.opener.location.reload(true);
    window.close();
    e.preventDefault();
  } else if (err) {
    router.replace('home')
    console.log(err)
    alert(`Error: ${err.error}. Check the console for further details.`)
  }
})
}

setSession (authResult) {
this.auth0.client.userInfo(authResult.accessToken, function(err, user) {
  localStorage.setItem('organization_id', user.organization_id);
});
// Set the time that the access token will expire at
let expiresAt = JSON.stringify(
  authResult.expiresIn * 1000 + new Date().getTime()
)
localStorage.setItem('access_token', authResult.accessToken)
localStorage.setItem('id_token', authResult.idToken)
localStorage.setItem('expires_at', expiresAt)
this.authNotifier.emit('authChange', { authenticated: true })
}
javascript popup authorization local-storage
1个回答
0
投票

问题是窗口在功能完成之前关闭。解决方案是在关闭弹出窗口时设置超时,如下所示:

// Do some function call

setTimeout(()=>{
   window.close()
}, 1500);
© www.soinside.com 2019 - 2024. All rights reserved.