Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

javascript - Cookies visible from URL bar but not visible in the Application tab of browser developer tool

If you go to didthanoskill.me and try to access cookies from the URL bar, you can clearly see "1 Cookie in use". On document.cookie in the console, empty string is returned. I thought the cookies must be HttpOnly so I headover to Application tab in browser dev tool and there also no cookies are showing. Weird!

Any idea why is so happening?

question from:https://stackoverflow.com/questions/65944205/cookies-visible-from-url-bar-but-not-visible-in-the-application-tab-of-browser-d

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rather than hard coding the cookie’s expire date to 27 Apr 2019 (which is a past date and how a cookie is deleted), you could use new Date and add some number of days for how long the status should last (I used 7 for my example).

function onLoad() {
    var displayElement = document.getElementById("display");
    var resultDate;
    var randomNumber = getCookie("thanosNumber");
    
    if (!randomNumber) {
        resultDate = new Date();
        resultDate.setDate(resultDate.getDate()+7);
        randomNumber = Math.random();
        document.cookie = "thanosNumber=" + randomNumber + ";expires="+resultDate.toGMTString();
    } else {
        randomNumber = Number(randomNumber);
    }
    
    if (randomNumber < 0.5) {
        displayElement.textContent = "You were slain by Thanos, for the good of the Universe.";
    } else {
        displayElement.textContent = "You were spared by Thanos.";
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...