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.
Related
This is code in which i am setting the cookie
document.cookie = 'cookie_consent=true; expires=Fri, 31 Dec 9999 23:59:59 GMT Secure';
Below is my code for checking cookie.
useEffect(() => {
const cookieValue = (`; ${document?.cookie}`).split('; cookie_consent=').pop().split(';')[0];
if (!cookieValue) {
console.log("Cookie not avaliable");
}
}, [document?.cookie]);
Cookie is getting expired after accepting within few days since i set cookie expiry as 31 dec 9999 etc.
Thank You in advance, Any help will appreciated.
As a side note, set useEffect with document.cookie as a dependence will not re-run when document.cookie change, it only accepts state dependencies
Also,
All the cookies expire as per the cookie specification. So, there is no block of code you can write in JavaScript to set up a cookie that never expires. It is just impossible and is a fact.
Solution: But you can set up a cookie that expires in JavaScript and pick some very large value as expiry date as specified below:
const expireDate = new Date(2147483647 * 1000).toUTCString();
document.cookie = `cookie_consent=true; expires=${expireDate} Secure`;
My assumption would be immediately that 9999 is too great as a year.
See the following post: https://stackoverflow.com/questions/10328361/maximum-lifetime-of-javascript-cookie#:~:text=The%20max%20value%20is%202,on%20the%20UNIX%20timestamp%20value.
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>
This issue is related to GDPR compliance but I'll keep it more focused on the technical issue at hand:
I have found some great open source resources for cookie consent banners, like Cookie Consent and Cookie Script. The implementation of the banner looks simple enough. The issue though is they require cookies to be disabled by default, which I am unsure how to do on a global level on a domain.
I don't know a lot of JavaScript but what I'm wondering is: Is there a method with Javascript to universally allow or deny cookies on a domain? Or, would this method be unique to each script in question? Google Analytics for example has documentation on disabling cookies. How would I lump that together with Facebook, Youtube, and all the other scripts using cookies and only allow cookies after a user has consented? Or, would I have to address it for each individual script?
In other words, is there a method in JavaScript where I can universally turn off/on cookies depending on user preference? Just from my research so far it seems there is not.
I have created a Proxy script on the document.cookie variable.
Run this script as the first script in your document.
Note
This solution assumes:
Cookies are set through javascript (and server side uses sessions).
It also only works on browsers which support the use of javascript proxies.
It only works for local domains (it only prevents external domain cookies from being set)
The Proxy script
Setting a cookie
What it does it that it intercepts the document.cookie variable because window.disableCookies is set to true in the script below. It stores the cookies in the window.cookieList array until the enableCookies script is executed. If enableCookies is executed, it will disable the proxy and iterate over the window.cookieList variable, to set the cookies in the browser.
Reading the cookies
If a script sets a cookie it expects the cookie in the document.cookie variable. So until the enableCookies function is called (and window.disableCookies is set to false), it fakes a document.cookie response, it builds it based upon the window.cookieList variable.
var cookie_setter_orig = document.__lookupSetter__("cookie").bind(document);
var cookie_getter_orig = document.__lookupGetter__("cookie").bind(document);
window.cookieList = [];
window.disableCookies = true;
Object.defineProperty(document, "cookie", {
get: function () {
if(!window.disableCookies) {
return cookie_getter_orig();
} else {
var response = "";
window.cookieList.forEach(function(cookie){
var splitted = cookie.split(";")[0].split("=");
response += splitted[0] + "=" + splitted[1] + "; ";
});
return response.slice(0, response.length - 2);
}
},
set: function (val) {
if(!window.disableCookies) {
cookie_setter_orig(val);
} else {
window.cookieList.push(val);
}
}
});
function enableCookies()
{
window.disableCookies = false;
window.cookieList.forEach(function(cookie){
document.cookie = cookie;
});
window.cookieList =[];
}
Testing it out
To test it out you can execute the following script:
/* These cookies are not set; they are set on the window.cookieList, until enableCookies is activated */
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/';
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/';
document.cookie = 'cookie3=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/';
/* This is a fake cookie list from the window.cookieList variable
* Output: cookie1=test; cookie2=test; cookie3=test
*/
console.log(document.cookie);
setTimeout(function(){
enableCookies(); /* Enable cookies and pass them to the browser */
/* The cookie below is passed to the browser directly, since cookies are enabled */
document.cookie = 'cookie4=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/';
/* This is the real cookie list
* Output: cookie1=test; cookie2=test; cookie3=test; cookie4=test
*/
console.log(document.cookie);
}, 2500);
Is there a method with Javascript to universally allow or deny cookies on a domain?
No.
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.
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