gpt4 book ai didi

javascript - 对 JavaScript 不调用的函数使用 Promise

转载 作者:行者123 更新时间:2023-12-01 00:52:50 24 4
gpt4 key购买 nike

我正在使用 Google 登录并遇到以下问题:

当我关闭浏览器并再次打开它时,

sessionStorage.getItem('userEntity') 返回null。如果我只是重新加载页面,它不会返回 null。

session 将在此函数中设置:

// Signing in
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();

// Store the entity object in sessionStorage where it will be accessible from all pages
let userEntity = {};
userEntity.id = profile.getId();
userEntity.name = profile.getName();
userEntity.img = profile.getImageUrl();
userEntity.email = profile.getImageUrl();
sessionStorage.setItem('userEntity',JSON.stringify(userEntity));

userIsLoggedOut.style.display = 'none';
userIsLoggedIn.style.display = 'flex';
document.querySelector('.user-img').setAttribute('src', userEntity.img);
}

我不在 JavaScript 中运行此函数。以下 HTML 将使其运行:

<div class="g-signin2" data-onsuccess="onSignIn"></div>

即使我将 console.log(sessionStorage.getItem('userEntity')) 放在函数后面或 JavaScript 的底部,它仍然返回 null。

我猜解决方案是使用 Promise,但是如果我不在 JavaScript 中运行函数 onSignIn() ,我该如何使用它?

最佳答案

当您关闭选项卡或浏览器时,SessionStorage 中存储的数据将被删除,更多详细信息如下: https://www.w3schools.com/jsref/prop_win_sessionstorage.asp

即使关闭选项卡或浏览器,您也可以使用 localStorage 将数据保留在浏览器中,因此请更改以下行:

sessionStorage.setItem('userEntity',JSON.stringify(userEntity));

localStorage.setItem('userEntity',JSON.stringify(userEntity));

但是您必须注意localStorage中存储信息的安全性,如果您需要在客户端存储安全数据,可以处理安全cookie。

关于javascript - 对 JavaScript 不调用的函数使用 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56843401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com