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
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>
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.
I'm setting a cookie but the problem is that when I look at the expiration date in the Chrome inspector, it's only showing as a session cookie. This is my code:
var ExpirationDate = new Date();
ExpirationDate.setDate(ExpirationDate.getDate() + 400);
document.cookie = 'eucookie=2;' + ExpirationDate.toUTCString();
What do I need to change to make it expire in 13 months (400 days) instead of at the end of the session.
You need to tell it that it's the expires property you're setting:
document.cookie = 'eucookie=2;expires=' + ExpirationDate.toUTCString();
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.