Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use localstorage for login using javascript

I'd written a code for login using javascript

function checkLogin()
{
    if(localStorage.login=="true")
    {
        window.location.href = "index.html";
    }
    else if(localStorage.login=="false")
    {
        window.location.href = "login.html";
    }
}

where localStorage.login="true" & "false" has been assigned from server dynamically

The page get looply redirected when i include this code!!

Give me solutions for :

How to remove / destroy user defined function after execution ?

or

How to execute user defined function for only one time ondeviceready in jquery

like image 374
Sundaravel M Avatar asked Apr 07 '26 13:04

Sundaravel M


1 Answers

I think the best solution would be to call this function from only the pages you want to redirect to the login and, as Emad Melad says, outside the login.html page.

If what you want is that people that go again to login.php page get redirected to index.php if they're logged in, you could try to detect which page you are in, and make an IF so if it's the login page it's not executed. It would be something like this:

function checkLogin()
{
    var url = window.location.pathname;
    var filename = url.substring(url.lastIndexOf('/')+1)

    if(localStorage.login=="true")
    {
        window.location.href = "index.html";
    }
    else if(localStorage.login=="false" && filename != 'login.html')
    {
        window.location.href = "login.html";
    }
}

* The snippet code to get the actual URL

However, from what I read in your code, you will be redirected the same to index.html from everypage that calls this function.

Usually, what I do in my apps is to check only if it's not logged in, and redirect to login.html if it's the case. What I'd do, modifying a little bit your function, is:

    function checkLogin()
    {
        var url = window.location.pathname;
        var filename = url.substring(url.lastIndexOf('/')+1)

        if(localStorage.login=="true" && filename == 'login.html')
        {
            window.location.href = "index.html";
        }
        else if(localStorage.login=="false" && filename != 'login.html')
        {
            window.location.href = "login.html";
        }
    }

That way, you will be only redirected to index.html if you are logged in and you are in login.php, and the other way you will be only redirected to login.html everywhere if you are not logged in, except for login.html.

Hope it can help you!

like image 166
Unapedra Avatar answered Apr 09 '26 01:04

Unapedra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!