IE doing logout after close the browser - javascript

I craete web-sites and when user login and check "remember me" I write to cookies username. It is working good, but just in some browsers.
My code for write in cookies username:
document.cookie = "";
document.cookie = "username=" + username;
And after login i check username from cookies.
But in IE browser it is not working.
After close the browser and open him again cookies doing clears.
Why it is happend?
And how to fix it?

I found good code for get/set cookies:
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) +
((exdays==null) ? "" : ("; expires="+exdate.toUTCString()));
document.cookie=c_name + "=" + c_value;
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Source:How do I create and read a value from cookie?
Thanks you heru-luin

Check this checkbox in browser settings: http://browsers.about.com/od/internetexplorertutorials/ss/ie8privatedata_8.htm

See the official MS Developer Network docs -> https://msdn.microsoft.com/en-us/library/ms533693%28v=vs.85%29.aspx
If you set no expiration date on a cookie, it expires when the browser
closes. If you set an expiration date, the cookie is saved across
browser sessions. If you set an expiration date in the past, the
cookie is deleted. Use Greenwich Mean Time (GMT) format to specify the
date.
So you basically need to specify an expiration date if you want the cookie to persist in IE. Example from the link above :
// Create a cookie with the specified name and value.
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue);
// Expires the cookie in one month
var date = new Date();
date.setMonth(date.getMonth()+1);
document.cookie += ("; expires=" + date.toUTCString());
}
Or see this excellent answer -> Using javascript to set cookie in IE.

Related

JavaScript cookies not working on sub-domains

I have a cookie authorization banner, with a button labeled 'Got it!' that dismisses it. I do that by setting a cookie.
To set a cookie, I have this in my <head>:
<script>
function setCookie(cname, cvalue, exdays)
{
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
var domain = ".brokenhearts.ml";
var security = "secure";
var location = "/";
document.cookie = cname + "=" + cvalue + ";" + expires + ";" + location + ";" + domain + ";" + security;
}
</script>
and I've set this to be executed when the button is clicked:
var privacyValue = "yes";
setCookie("privacy", privacyValue, 365);
The problem is, when I check for the cookie in Chrome, it shows me something like this:
As you can see, the cookie is getting set only for www.brokenhearts.ml and not for its sub-domains. I want the cookie to be set for all sub-domains.
I tried setting the cookie with the domain as "brokenhearts.ml" and it still gets set only for www.brokenhearts.ml.
When setting up the cookie, your domain must be in format of .domain.com – dot and root domain and path=/, always.
If you don't set path=/, auto path will be saved as from where the cookies is being saved - hence it wont be accessible across any subdomain.
//variables
var LastReportGenerated="Jul 11 2013",
baseDomain = '.cssjunction.com',
expireAfter = new Date();
//setting up cookie expire date after a week
expireAfter.setDate(expireAfter.getDate() + 7);
//now setup cookie
document.cookie="Report={'ReportName':'MainReport', 'lastGenerated':" + LastReportGenerated + "}; domain=" + baseDomain + "; expires=" + expireAfter + "; path=/";
Source:
How to set cookies to share across all subdomains using JavaScript

How to clear session when reopen the closest tab in a browser

I can invalidate session when i close the tab or windows of browser, but when i click to reopen the closest tab it loads me the recent page as it is.
I want to redirect to login page if the reopen is clicked, I clear the cookies onUnbeforeUnload but it doesn't work.
here is my code:
`$(window).on("beforeunload", function(e) {
var aCookies=document.cookie.split('; ');
for (var i = 0; i < aCookies.length; i++) {
var cookie = aCookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + '=0; expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';
}
window.location.href = "/safe-unsecured/logout";`
}
and on load of the page i clear cookies;
Any help would be appreciated
browsers will not load a new page on closing or browsing away from a page. That logout page will never be requested.
Also, as long as the browser is not restarted, the session will exist in the browser. A session is not invalidated by a tab closing, but by the entire browser closing. The only way to really achieve what you want is having your cookies live for one minute and have a timer running that updates the cookie expiry every 10 seconds so it doesn't expire as long as the page is open, or the tab isn't re-opened within a minute.
This is an example of the update code. You'll need to add logic yourself that checks for the existance of the cookie and everything else you need for validation.
window.myCookieValueThatIReadBefore = 'Hello';
window.setInterval(function() {
setCookie('cookie_name', window.myCookieValueThatIReadBefore,1)
}, 1000*10);
function setCookie(cname, cvalue, exminutes) {
var d = new Date();
d.setTime(d.getTime() + (60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

Disabling a JavaScript function with a Cookie

I am working on a mobile part of my site and I would like to disable a welcome message which is produced by a JavaScript function when the page loads.
What I am trying to do is to disable that function with a cookie that has the expiration time of 20 minutes.
This is how far I've gotten with the cookie:
// c_name = cookie name
// c_value = cookie value
// ex_min = expiration in minutes
function setCookie(c_name, c_value, ex_min) {
var d = new Date();
d.setTime(d.getTime() + (ex_min*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = c_name + "=" + c_value + "; " + expires;
}
// Cookie that lasts for 20 minutes.
setCookie("last-visited", "1", 20);
What I can't figure out is how to disable that function from within the cookie.
And yes, the cookie is from w3schools.com.
Any help is appreciated.
Thanks.
I guess you need something like this
var lastVisitedCookieName = 'last-visited';
if (!document.cookie.contains(lastVisitedCookieName))
{
alert('Welcome');
setCookie(lastVisitedCookieName, "1", 20);
}

The cookie is deleted when the browser is closed

I have this cookie to store users previous selection from a menu. But I want keep this cookie stored in the browser even if the user closes the browser. This code perfectly works on IE but when I close Chrome and Firefox, the cookie getting deleted. Can anyone provide me solution for this.
function setCookie(NameOfCookie, value, expiredays) {
var ExpireDate = new Date();
document.cookie = NameOfCookie + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}
function delCookie (NameOfCookie) {
if (getCookie(NameOfCookie)) {
document.cookie = NameOfCookie + "=" + "; expires=Thu, 17-Jul-24 00:00:01 GMT";
}
}
If you call the function with
setCookie('redirectcountry', 'CA')
then you set the expiry date to new Date(), that is "right now". So it's normal behavior to have the cookie be immediately deleted.
Simple solution : call it as
setCookie('redirectcountry', 'CA', true)
Did you check your browsers settings? In Firefox this is option called 'Keep until' with value 'I close Firefox' (Privacy tab).

How to create a global cookie in javascript?

I've created a Django website, and need a cookie to be stored and readable from any part of the site. The javascript for it is in every part I need it in, but for some reason the cookie itself is stored seperately for each page. E.g. if the cookie is equal to "set" on one page, it can be undefined on another. Here's the code I'm using to create, get, and read the cookie (the "createBannerCookie()" method is called when a specific button, found on every page, is pressed)-
<script type="text/javascript">
$(document).ready(function() {
$('#banner').hide();
checkBannerCookie();
});
function createBannerCookie()
{
$('#banner').hide();
var exdate=new Date();
exdate.setDate(exdate.getDate() + 3);
var c_value=escape("set") + ((exdate==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie='banner=' + c_value;
}
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function checkBannerCookie()
{
var banner=getCookie("banner");
if (banner!=null && banner!="")
{
$('#banner').hide();
}
else
{
$('#banner').show();
}
}
</script>
Any suggestions?
By default, cookies are accessible only to web pages in the same directory as the web page which originally created the cookie. Please try to add "path=/" option. e.g.
document.cookie =
'propertyName=test; path=/'
SImon,
I think your problem is the expiration date on your cookies. It looks to me like you are setting them to expire 3 miliseconds after being created.
Try something like this in your "createBannerCookie" function (instead of the w3schools version):
function createBannerCookie()
{
$('#banner').hide();
var exdate=new Date();
exdate.setTime(exdate.getTime()+(3*24*60*60*1000)); // the 3 in that math is your days
var c_value=escape("set") + ((exdate==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie='banner=' + c_value;
}
Reference: http://www.quirksmode.org/js/cookies.html

Categories

Resources