I'm trying to set a cookie that will expire in a given amount of time. When the cookie is active (i.e. not expired) a div will be displayed. Once the time has expired the div will not be displayed and never again be displayed.
The cookie needs to be set on first page load and the expire date set.
I don't think the cookie needs to ever be deleted because that would then cause the cookie to be recreated.
So I guess I need to somehow check if the cookie has expired, not if it still exist. I can't find any information on how to check if a cookie has expired, only if it exist.
I'm new at cookies but here is my latest attempt:
if (document.cookie.indexOf("test=") >= 0) {
}
else {
// set a new cookie
expiry = new Date();
expiry.setTime(expiry.getTime()+(2*60*1000)); // Two minutes
// Date()'s toGMTSting() method will format the date correctly for a cookie
document.cookie = "test=" + expiry.toGMTString() +"; expires=" + expiry.toGMTString() +"; path=/";
if (document.cookie.indexOf("test=" + expiry.toGMTString() +"")){
//stuff here
}
}
I know it's probably way off. Also I have js.cookie.js installed just in case I needed it.
Related
Using cookies, i am trying to just show a alert message and a blinking status message that cookie is getting expired in like a countdown, giving them 60 seconds to click, extend it, if they do not click the link, it will navidate to the href link for expiration. and will expire the cookie.
<script>
//the function IdleToLong will be called after 30seconds.
//This means if the page reloads, it starts over.
setTimeout(IdleToLong, 30 * 1000); // 30 seconds
function IdleToLong() {
alert('Move your ass');
//If you also need to logout in PHP then you must notify the server that a user has been idle to long.
$.get('logout.php?reason=idle').complete(function() {
window.location.href = '/';
});
}
</script>
the above code works but it does not display a message like a countdown from 60 backward to 0, in that alert, if they click, expend, extend the cookkie, else logout, but that alert should only appear after every 3 hours, because i am setting it for 3 hours and extending it by 3 hours
That's not that simple, JavaScript cannot retrieve the expiration time of a Cookie in the document.cookie API or in the Response object in case of a fetch or XMLHttpRequest. So you'll have to provide the token from the backend in a readable header (or in the body). Then you'll be able with some simple logic to code the countdown in JavaScript.
To give more concrete examples, this header is not retrievable in JavaScript:
Set-Cookie: test=value; Path=/; Expires=Sat, 28 Mar 2020 12:48:58 GMT;
After this header has arrived in a HTTP response, the cookie is retrievable with document.cookie but without the expiration date.
On the other hand, this header is retrievable:
X-Whatever-Name-You-Want: test=value; Path=/; Expires=Sat, 28 Mar 2020 12:48:58 GMT;
So you could provide the Cookie in a custom header in order to retrieve it with JavaScript with the expiration date.
When a user visits your site and you set a cookie, you should set a second cookie containing the first cookie's expiration date. Then using JavaScript you can subtract the value of the expiration date from the current time to get your setTimeout value.
PHP:
$cookie_max_age = [number of seconds];
$cookie_expires = time()+$cookie_max_age;
$cookie_value = rawurlencode("[cookie value]");
header("set-cookie: [cookie name]=$cookie_value; max-age=$cookie_max_age", false);
header("set-cookie: expires=$cookie_expires; max-age=$cookie_max_age", false);
JavaScript:
var expires = parseInt(('; '+document.cookie).split('; expires=')[1]);
var interval = setInterval(function() {
var milliseconds_left = (new Date()).getTime()-expires*1000;
if (milliseconds_left<=0) {
clearInterval(interval);
$.get('logout.php?reason=idle').complete(function() {
window.location.href = '/';
});
}
else if (milliseconds_left<=60000) {
var messageBox = document.getElementById('messageBox');
messageBox.innerHTML = "Your session will expire in "+(milliseconds_left/1000)+" seconds.";
}
}, 1000);
Doing a countdown is a different problem. You probably want to create a lightbox with an extend button.
I have a code that needs to run a count-down timer, the counter needs to count down 15 min per user even if he\she leaves the page.
this is the cookie initialize line:
document.cookie = "name=timerCookie; timeLeft=" + initialTime + "; expires=" + expires;
and this is how I update the cookie:
document.cookie = "name=timerCookie; timeLeft=" + timeLeft + "; expires=" + expires;
when I try to read the cookie I get "name=timerCookie"
am I setting the cookie correctly?
can I use cookie this way?
EDIT****:
apparently, cookie can contain only 1 segment(aka timeLeft) by removing the name value the issue was solved.
Well, I came up with this solution while I was offline and before I learned what your use case actually is.
I was thinking it would be better to use localStorage since MDN says:
"Cookies were once used for general client-side storage. While this was
legitimate when they were the only way to store data on the client, it
is recommended nowadays to prefer modern storage APIs."
Since your server needs to know about the user's "time remaining", you probably want cookies after all (unless you can just have the browser update the server at unload time), but maybe you can adapt this idea to your purpose.
I was also thinking that "even if he/she leaves the page" meant that the timer should keep ticking while they're away -- but this part should be relatively easy to fix.
I'm including this as HTML (to copy/paste) because SO snippets are sandboxed and won't run code that uses localStorage.
<!DOCTYPE html><html><head></head><body>
<p id="display">__:__</p>
<script>
let expires = localStorage.getItem("expires"); // Gets the stored expiration time
const display = document.querySelector("#display"); // Identifies our HTML element
// Makes a helper function to treat dates as accumulated seconds
const getSecondsSinceEpoch = ((date) => Math.floor(date.getTime()/1000));
// Sets the expiration time if countdown is not already running
if(!expires){
expires = getSecondsSinceEpoch(new Date()) + (60 * 15); // 15 minutes from now
localStorage.setItem("expires", expires);
}
// Calculates how long until expiration
let pageLoadedAt = getSecondsSinceEpoch(new Date());
let secondsRemaining = parseInt(expires) - pageLoadedAt;
// Starts the countdown (which repeats once per second)
setInterval(countdown, 1000);
function countdown(){
// When time expires, stops counting and clears storage for the user's next visit
if(secondsRemaining === 0){
clearInterval();
localStorage.clear(); // You don't want this here -- it resets the clock
}
else{
// Until time expires, updates the display with reduced time each second
display.textContent = formatTime(--secondsRemaining);
}
}
function formatTime(time){
let mins = Math.floor(time/60).toString();
let secs = Math.floor(time%60).toString();
secs = secs.length == 2 ? secs : "0" + secs; // Ensures two-digit seconds
return `${mins}:${secs}`
}
</script>
</body></html>
We have a webshop. We use a cookie that stores the order ID of every single order/user. All of the items in the basket and the user's address info are related to that ID. The cookie is only meant to be changed when an order is complete or if its value is empty. We check the cookie with the server on each page load and only change it when conditions above are met.
A few months ago, we discovered that in some cases, the browser can keep multiple versions of that cookie value, and "switch" between those values randomly on page load. Moreover, the value is not overwritten - if the browser switches from value A to value B, a few page loads later it can load value A again. The browser can hold up to 5 (possibly more) values for a single cookie, and it keeps changing them randomly as the user navigates our webshop. It is very problematic since once the cookie value is changed - the basket contents changes with it. We experienced this problem primarily in Google Chrome and Internet Explorer. Trying to check the cookie value in the console shows only the value that is being used for the current page load.
We use the following function to set cookies:
function SetCookie(c_name, value, exdays){
var expires = "";
if(exdays)
{
var date = new Date();
date.setTime(date.getTime() + (exdays*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = c_name + "=" + escape(value) + expires + "; path=/";
}
Whenever I read about cookies, everyone says that overwriting a cookie with the same name and path is supposed to destroy the previous value. So I tried to do the following when setting the order ID cookie (delete cookie before setting it):
SetCookie(name , "", -1);
SetCookie(name , val, 14);
However, the problem still persists and the browser keeps randomly choosing the value on page load. What could be causing such behaviour? Is there any way to check the (shadow) values of the cookie that the browser is currently NOT using? Is there any way to check how many values for a specific cookie name and path the browser has stored?
EDIT: Our javascript order ID cookie setter function runs on page load. It is the only place we ever change the order ID cookie.
Recently, we tested this behaviour with dev tools open and it showed interesting results. A simple page reload can change the cookie header of the request to a request containing a different cookie value, before our cookie setter function ever had a chance to run. We thought it could be a caching issue (request being cached and used later), but it seems this behaviour persists when we set up the server to return a no-cache and no-store response header.
Look at the Nate answer to this question How to handle multiple cookies with the same name?
Hope it helps !!
I want cookie to expire when session of user expires. It can be pure in javascript, XPages-SSJS.
On each page load set the cookie to expire on the current time + the length of the session.
For example, if your session is 1 hour long, add this on page load:
var time = new Date().getTime(); // get the current time
time += 3600 * 1000; // add 1 hour to the current time
document.cookie = 'cookiedata=' + cookiedata + '; expires=' + time.toGMTString() + ';';
In this example, cookiedata is whatever you are storing in the cookie.
The code on this XSnippet can be used behind a Logout button. This will clear the sessionScope variables for an 8.5.x server, but will not for a 9.0 server:
http://openntf.org/XSnippets.nsf/snippet.xsp?id=clear-session-whole-server
If you want to clear the sessionScope map on R9, you'll need to get a handle on the map, iterate the keys and clear them, as in this XSnippet:
http://openntf.org/XSnippets.nsf/snippet.xsp?id=clear-session-current-nsf
Here is an example how to modify the expiration date of the session cookie from server side:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.beforeRenderResponse>
<![CDATA[#{javascript:var sessionId = facesContext.getExternalContext().getRequest().getSession().getId();
var response = facesContext.getExternalContext().getResponse();
var maxAge = facesContext.getApplication().getApplicationProperty("xsp.session.timeout", "30");
var maxAge = maxAge * 60;
response.addHeader("Set-Cookie","SessionID=" + sessionId + "; path=/; max-age=" + maxAge)}]]>
</xp:this.beforeRenderResponse>
</xp:view>
But keep in mind that setting an expiration of a cookie will have some side-effects, f.e. if you are closing the browser the cookie will not be removed automatically. Because the cookie is is valid for the whole server (path=/), this can affect other applications running on the same path too.
onClick="javascript:document.cookie='n=1'"
Im new in javascript
I have a btn click will set cookie, how can I set expire time 1 hour on this cookie?
When you write the cookie to the browser, you need to specify an expiration date or a max age. However, note that max-age is ignored by Interent Explorer 8 and below. So if you're expecting to get usage from that browser, you can just rely on expires.
Example:
<script type="text/javascript">
function setMyCookie() {
var now = new Date();
var expires = new Date(now.setTime(now.getTime() + 60 * 60 * 1000)); //Expire in one hour
document.cookie = 'n=1;path=/;expires='+expires.toGMTString()+';';
}
</script>
And your button can call this function like so:
<input type="button" onclick="setMyCookie();">Set Cookie</input>
Note that I've also included the path to indicate that this cookie is site-wide.
You can read more about expiring cookies with the date or max-age here:
http://mrcoles.com/blog/cookies-max-age-vs-expires/
You can do:
onClick="setupCookie();"
function setupCookie() {
document.cookie = "n=1";
setTimeout(function() {
document.cookie = "n=0";
}, 3600000); // 1 hour
}
On click you can call some javascript function and while creating cookie itself you can set expire time please refer this
javascript set cookie with expire time