Cookie not being deleted after session closed - javascript

I'm using cookies that should be deleted after user closes the page, but they're not. This is how I set cookies with JS
document.cookie="status=false";
I can see the cookie in console and after I close browser and open it again and go to my webpage there's still cookie status=false any idea why?

I solved it with this "trick", I don't know why I can't get cookies to work
window.onbeforeunload = function() {
document.cookie="status=false";
};

document.cookie = ... sets individual cookie values, it does not set "the entire cookie" to the string you passed, so setting "status=false" simply binds or updates the "status" value, irrespective of whatever else is in the cookie:
document.cookie = "cow=bell";
document.cookie = "cat=lol";
// cookie is now "cow=bell&cat=lol", not just "cat=lol"
If you want to delete the entire cookie, set its expiration time to "in the past" and the browser will do the cleanup for you.
(As pointed out in a comment, if you never set an expiration timestamp for your cookie, it'l expire when the page session ends, e.g. you close the tab/browser)

I was actually doing this today. A great reference is the Mozilla cookie documents if you create a js with their var docCookies code then using the functions provided like docCookies.setItem() docCookies.setItem() docCookies.getItem() or docCookies.removeItem() work incredible well.

Related

Javascript cookie removed after leaving page

I'm attempting to create a cookie the first time a user visits a page on the website and store the pathname as the value of the cookie for that page for records.
I'm attempting on doing this by creating a function at the page load called GenerateCookie.
This function then checks to see if the cookie reportingpage exists or not and if it does not exist create the cookie. I would like the value to remain the same until the session is over. I am attempting to record the first page visited. So for example, if a user visits /testing-page/ I would like the cookie value to remain /testing-page/ even if they back out of the page and visit other pages, since that was the first page visited.
Currently, the cookie is created as expected with the pathname value as expected, but any time I back out of the page and visit a new page the cookie is then removed and set with the other pages pathname value. I've attempted to fix this issue by including the path= attribute when setting the cookie, but this has no effect.
How can I create a cookie and keep that same value for the entire session until the tab/browser is closed?
Here is a code snippet of my code:
GenerateCookie();
function GenerateCookie() {
// if cookie does not exist, create cookie reporting page
if (document.cookie.indexOf('reportingpage=') == -1) {
console.log('no cookie')
document.cookie = "reportingpage=https://www.testing.com" + window.location.pathname + "; path=/"
} else {
// if cookie exist, get value
console.log('cookie exist')
const name = "reportingpage"
const match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)'));
console.log(match[1], 'value')
}
}
Storing a hundred cookies on someone's computer is really unethical, especially if it's for tracking their page visits. I'd be super annoyed if I visited a site and suddenly have a gazillion cookies to delete. But perhaps you have good reasons so if you really have to do it then use localStorage instead of cookies.
sessionStorage.setItem('someKey', window.location.pathname)

HTML5 LocalStorage to maintain session across pages/tabs under same domain

Anyone provide me way, I can use HTML5 LocalStorage to use in Javascript to maintain session between server and client to keep track of session Timeout which will redirect the all tabs or pages in session Expired page.
Is there any way(Other than this) i can maintain session across the page/tabs under same domain to keep track of Session Timeout.
Thanks in Advance
You have not posted any code so the only think I can do for you is just show you a generic example which may not completely suit your requirement but will give an idea on how you could do it:
// show last settings pane if it's set
if ( localStorage.activePill ) {
$('.nav-pill-control > li').removeClass('active');
$('.nav-pill-control > li > a[href="' + localStorage.activePill + '"]').parent().addClass('active');
$('.nav-pill-pane').hide();
$(localStorage.activePill).show();
}
The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.
In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
More Information

JavaScript: sessionStorage loses item

I have following JavaScript code in the Layout-Page of my ASP.NET MVC application to store a browser wide Id for an user as a cookie so I can access information in the session on server-side for the respective user.
if (sessionStorage.getItem("TestWindowId") == null) {
sessionStorage.setItem("TestWindowId", "#Guid.NewGuid().ToString("N")");
$.removeCookie("Test_Cookie");
storeWindowIdInBrowserWideCookie();
window.location=document.URL;
}
if ($.cookie("Test_Cookie") !== sessionStorage.getItem("TestWindowId")) {
$.removeCookie("Test_Cookie");
storeWindowIdInBrowserWideCookie();
window.location=document.URL;
}
function storeWindowIdInBrowserWideCookie() {
var cookieValue = sessionStorage.getItem("TestWindowId");
if (cookieValue != null) {
$.cookie("Test_Cookie", cookieValue);
}
}
In most cases this works.
But in some random cases for some users the sessionStorage.getItem("TestWindowId") returns null on the same browser tab it was definitely set before. In those cases I lose the Id and although the connection to the user information on server-side. According to my logs the sessionStorage item was set and in a callback call within the same second the sessionStorage of the same browser tab was null again.
What can cause the sessionStorage on client-side to lose items?
Or is there a error in my logic?
UPDATE:
There was a problem in my thinking pattern. The problem is not that the sessionStorage item was deleted but that the wrong cookie value was sent with the request to the server.
I opened another ticket since the question differs:
Store browser window specific id in cookie
As per the docs.
sessionStorage is similar to Window.localStorage, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or closing window will cause session storage to expires.
So it may happen that client has closed the browser or open it in a new tab.

How to avoid duplicate cookies

In my application I set a cookie using jQuery Cookie Plugin v1.4.1 (https://github.com/carhartl/jquery-cookie) like this:
$.removeCookie("Test_Cookie");
$.cookie("Test_Cookie", "xxx");
I want this cookie to only exist once but under some circumstances the cookie exists twice.
How is that possible and what is the best practice to make sure a certain cookie exists only once?
You can use the String.prototype.split() to convert document.cookie to an array of key value strings (key=value), then you can iterate over these, split them, and if the key is the value, break. Please see below for an example:
function checkCookieExists( cookieName ){
var cookies = document.cookie.split(';'); //returns lots of these: key=value
var toCheckCookie = cookieName; //checks if this cookie exists
cookies.forEach(function( cookie ){ //foreach cookie
var key = cookie.split('=')[0]; //the key cookie
if (key.toLowerCase() === toCheckCookie) //if the current key is the toCheckCookie
{
return true;
}
});
return true;
}
One way to get duplicate cookies is to have a page at company.com and another page at dev.company.com. Then requests to dev.company.com will get cookies for domains .company.com and .dev.company.com. The HTTP responses from dev.company.com can never change the cookies the browser is storing for company.com. This means you cannot "clear" all the duplicate cookies with HTTP response from dev.
This can be frustrating because often the library to handle cookies will only return a single cookie for a key. A valid HTTP cookie header is "Cookie: zyx=data1; zyx=data2" Then your library will return only one of these, likely the first one.
A common solution for this is to use a different cookie key for different domains: "Cookie: dev.company.com-xyz=data1; company.com-xyz=data2"
Another solution is to get the HTTP Cookie header, parse it while handling multiple cookies and use the first one that is valid. Like with a valid auth or a valid JWT.

PhantomJS setting cookies as Read and Write

I am trying to login to a website with phantomJS by session AUTH cookie, I finished the code for it and everything is working perfect, the problem is the website have like another login system inside with the same cookie, once accessed the other page cookie will update the security auth token, so when I add the First cookie to phantom I see that it is set to read Only because i cant access what is inside the second login system as Website is trying to update the Cookie that I manually added but unfortunately it fails because the cookie is Set to read Only.
code I am using :
phantom.addCookie({
'name': 'some name here', /* required property */
'value': 'some hash here',
'domain': 'ea.some domain here.com', /* required property */
'path': '/',
'httponly': false,
'secure': false,
'expires': (new Date()).getTime() + (10000 * 60 * 60) /* <-- expires in 10 hour */
});
I tried to delete the session cookie before my script auto access the page that needs second Auth but it just log me out because i need to have my old Session auth so it can be updated with the new session authhash.
any ideas how to make manually added cookies to be updated once requested from server side ?
I found the solution,
It appears that server actually created a new cookie with the same name and new value. not by replacing it with the new value. I searched the web for any help regarding this matter but I failed, I fixed this problem by taking the value of the new cookie and saving it to a variable, then executing phantom.clearcookies() to remove all the cookie and adding the new cookie again with the new value that I stores, It was not clean but it did the trick.

Categories