Javascript cookie removed after leaving page - javascript

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)

Related

Run different js on each user visit

I want to load javascript functions on a wordpress site based on user visit, if it's the first time, then one function will run, if its second visit another code will run., I found that using cookies and local storage we can set it, but only track user if visited or not., I want to count the user visit, and based on that run the functions.
var first_visit = false;
checkFirstVisit();
function checkFirstVisit(){
if(localStorage.getItem('was_visited')){
return;
}
first_visit = true;
localStorage.setItem('was_visited', 1);
}
console.log(first_visit);
this code is to track the first visit, How do I make it to track the number of visits?
You can use session storage in PHP (https://www.w3schools.com/php/php_sessions.asp) to store in a variable whether this is the user's first visit or not.
Then using an if-else statement, display the required code.
The good thing about PHP session storage is that it can retain the storage even after the user closes the browser.
it is the same thing
set a cookie for visiting
if it is not set so it is the first visit so set it to 1
if it is 1 so second visit so set it to 2
if it is n so it is n + 1 visit so incrment n

How to redirect new visitor to a landing page?

So basically i need a redirect to a landing page but this code: How to redirect first-time visitors to another page? worked when I tested it first and now it's not working and I even tested the ones in the comments or reply.. please help.
Creating the cookies script is not working
You can use LocalStorage instead of cookie:
if(!("visited" in localStorage)){
localStorage.visited="";
window.location="https://google.com/";
}
You can use localStorage instead of cookie. It has 5 mb limit of memory per domain. First check if isNewVisitor is null .If the user never visited the site, then set it to true and redirect to you homepage. if the user visits 2nd or 3rd time, it goes else if block and sets isNewVisitor to false.
var homePage= 'www.yourwebsite.com'
if(localStorage.getItem('isNewVisitor') === null){
localStorage.setItem('isNewVisitor') = true;
window.location = homepage;
}else if(localStorage.getItem('isNewVisitor')){
localStorage.setItem('isNewVisitor') = false;
}

Do i have to use Session Storage or LocalStorage : javascript AWS

I have below scenario
Page 1 has a link, when user clicks on it, it gets navigated to portal page with page reload. So just before navigation, a JSON object is created
The size of this object comes around 4KB roughly.
Sample object
let obj = {
"date":"12/31/2018",
"year":"2019",
"zip":"93252",
"members":[
{
"sdf":true,
"age":21,
"fdssss":false,
"aaaa":false,
"fdss":null,
"fsdfsd":[
"ADULT"
]
},
{
"sdf":true,
"age":21,
"fdssss":false,
"aaaa":false,
"fdss":null,
"fsdfsd":[
"ADULT"
]
}
}
There is a back link from that portal page, on clicking page will be navigated back to Page 1 with a page reload.
So when the page is navigated back, I need the created JSON object back again. I need it only for that session or the data should be persistent even if the page is reloaded.
Do I have to use localStorage? If i store the object in localStorage, at what point i should clear the storage? How should I handle between different users?
Do I have to use sessionStorage? what will be the scope of the data availability
I'm using AWS service.
Q1:
you can have localStorage, and you should handle it at the code when first page loaded and you can delete it when user do signout or login, storage is about browser not user, if there are some users behind one computer at different times you must clear all data manually.
Q2:
you can also have sessionStorage, per tab and will be removed by closing browser.
in details:
This is depends on your scenario which means localStorage used for long time but sessionStorage used when you need to store something temporary.
but the important thing about sessionStorage is that it is exist per tab if you close tab and windows the sessionStorage completely removed, it used for critical data such as username and password whereas localStorage is used to shared data whole the browser.
localStorage has no expiration date, and it gets cleared only by code, or clearing the browser cache or locally stored data whereas sessionStorage object stores data only for a session, meaning that the data is stored until the browser (or tab) is closed.
at the end I suggest you to use localStorage because you may want to share that data whole the browser event after closing browser and you can store more data, in the other side there are limitation about them, when you are used storage you should handle them manually and take care.
suppose:
function removeStorage()
{
var obj = localStorage.getItem('obj');
if(obj !== null)
localStorage.removeItem('obj')
}
and in login or logout success action call removeStorage() and in Page1 load have something like below:
var obj = localStorage.getItem('obj');
if(obj !== null)
{
....
//show the obj in label or do what you want with it
...
}

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.

Cookie not being deleted after session closed

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.

Categories