Friday 9 August 2013

Automatically log users into your website using HTML5 Local Storage

So your users has been registered. They have gone through the pain of logging in on a mobile phone and you want them to authenticate more easily next time round, so that they don't give up on using your web app.

The solution : HTML5 Local Storage. In the code below, I take the username and password, and put them in localstorage variables. When the (login) page is visited again, I check to see if those localstorage variables exist. If they do, I add them as values to the username and password field, and perform a submit.

Enjoy!

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>HTML5 Save Password</title>
<!--[if IE]>
<script src="html5.js"></script>
<![endif]-->
<script src="jquery.min.js"></script>
</head>
<body>
<form method="POST" action="set.php">
<label for"username">Username</label>
<input name="username" type="email" />
<label for"password">Password</label>
<input name="password" type="password" />
<input type="submit" />
</form>
<script>
(function()
{
u = false;
p = false;
if(localStorage.getItem('username') != null)
{
$('form input[name=username]').val(localStorage.getItem('username'));
u = true;
}
if(localStorage.getItem('password') != null)
{
$('form input[name=password]').val(localStorage.getItem('password'));
p = true;
}
if((u == true) && (p == true))
{
$('form').submit();
}
$('form').submit(function()
{
localStorage.username = $('form input[name=username]').val();
localStorage.password = $('form input[name=password]').val();
});
})();
</script>
</body>
</html>

No comments:

Post a Comment