Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

237
Views
JavaScript code that's supposed to return the user to a login page if a cookie doesn't exist, doesn't work

So I have multiple pages connected that should check if a cookie exists when first visited, as the cookie wont exist it should send the person to the login page where after put in their username, password and time limit for the cookie, the script creates a cookie and redirects them back to the index page. Now everything works besides the redirecting part, because I'm guessing its not fetching the cookie right so it keeps sending you to the login page as soon as you get redirected to where you were supposed to.

function upisi_cookie() {
var danas = new Date();
var istice = new Date();
var username = document.prijava.username.value;
var password = document.prijava.password.value;
var trajanje = parseInt(document.prijava.trajanje.value);

istice.setTime(danas.getTime() + (trajanje * 1000));
let expires = "expires=" + istice.toUTCString();
document.cookie = "User=" + username + ";" + expires + ";path=/";}

Above is the cookie creation code. And this is for fetching the cookie and checking weather it exists or not (and redirection if it does exist)

function getCookie(User) {
    var dc = document.cookie;
    var prefix = User + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
    }
    return decodeURI(dc.substring(begin + prefix.length, end));
}
window.onload = function ControlCookies() {
    var myCookie = getCookie(User);
    stranicaCurrent = document.getElementsByTagName("title");
    if (myCookie == null && stranicaCurrent != "prijava") {
        window.location.href = "---login page location---"; //sends the user to a login page if there are no cookies
    }
    else {
    }
}

 
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!