javascript - 如何在浏览器本地存储中存储数据

标签 javascript html local-storage

我尝试不使用数据库,而是使用浏览器本地存储作为登录示例。我的意思是,当用户提供“用户名”和“密码”时,它将从浏览器本地存储中进行检查,然后才能登录。 我正在使用 HTML5 的 localStorage.setItem 和 localStorage.getItem 来获取数据并显示它。 这是我的代码-

var user_name=document.getElementById('userName').value;
var user_pswd=document.getElementById('password').value;                  
localStorage.setItem("user", user_name);
localStorage.setItem("pass", user_pswd);                    
// Retrieve                    
document.getElementById("output").innerHTML = localStorage.getItem("user");

它设置了数据并显示了用户名,但是重启浏览器后是否可以获取数据??当我第一次尝试登录时,如何检查浏览器数据?非常感谢任何帮助..

最佳答案

重启浏览器不会删除本地存储数据。

您可以使用以下条件检查您是否拥有两个 key (用户名、密码)的数据

if ((localStorage.getItem("userName") !== null) && (localStorage.getItem("password") !== null))
{
    // you have values for both userName and password
}

对于您的情况,您可以测试文本框值是否与本地存储中的值匹配

if ((localStorage.getItem("userName") === null) && (localStorage.getItem("password") === null))
{
    localStorage.setItem("user", "Subho"); // writes name and password to local storage if not exists
    localStorage.setItem("pass", "Subho"); 
}

if ( (localStorage.getItem("user") == document.getElementById('userName').value)
{
    if ( (localStorage.getItem("pass") == document.getElementById('password').value)
    {
        // login is successful
    }           
}

但是这不是一个安全的登录方法,用户可以访问本地存储数据

关于javascript - 如何在浏览器本地存储中存储数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26646096/

相关文章:

javascript - 从外部 View 动态添加 html

html - CSS 下拉 <ul> <li> 菜单每一层大小不同

flutter - 为什么在 Flutter 中必须使用 await 来保存/获取本地数据?

java - 基于磁盘的列表实现

javascript - 删除本地存储

javascript - IndexedDB 搜索键并排序

javascript - Promises 有 'finally' 模式吗?

javascript - 使用 firebase auth 获取用户详细信息,其中条件是多个电话号码?

javascript - 将一个 div 放在另一个后面但仍然显示在上面?

html - 使用 html 的 iframe 菜单