How to properly control the google analytics cookie from javascript? - javascript

Currently I have set up the cookie prompt to override document.cookie set method, so that it stores non-required cookies and waits for user input (which cookies the user allows to use in the web page) to decide about other cookies.
Code looks something like this:
const originalSetter = document.__lookupSetter__('cookie');
function newSetter(cookie) {
if (isRequired(cookie)) {
originalSetter(cookie);
}
else {
//store the cookie and decide later.
}
}
document.__defineSetter__('cookie', newSetter);
Since the google analytics cookie is not a required one (at least in my page), is this the correct approach or is there another way to do this?

Related

email and password remember me for login after user logged in for the first time

when the user login to his account and click remember me how to make the login form auto-fill the user email and password when the user come to login again so he doesn't have to fill his email and password again in react and next
First of all, store user's credentials on front side (localStorage, lessionStorage and etc.) is not a good practice.
Usually "Remember me" checkboxes are used to create an auth-cookie with longer time life.
For example:
When user checked "Remember me", you will send post request with query params remember=1, server handle this, and send response with header:
Set-Cookie: {auth-cookie}={value}; Max-Age={one week, for example}
It will create a cookie in browser, which time life is one week.
In another case, if user didn't check "remember me", server responds with header like this:
Set-Cookie: {auth-cookie}={value}; Max-Age={one day, for example}
It means that user will be authorized during just one day, after it cookie will be expired, and user will logged out.
User can allow the browser to autocomplete input fields if click "Save password" after submitting the form in browser's popup.
It's browser behavior.
Best regards!
Answer
You can use localStorage, a built-in object in JavaScript for browsers.
localStorage is of type Storage, which means that you can use it via the methods setItem, getItem, and removeItem.
How to use
localStorage.getItem("item1"); // null
localStorage.setItem("item2", "EntityPlantt");
localStorage.getItem("item1"); // still null
localStorage.getItem("item2"); // "EntityPlant"
localStorage.item1; // "EntityPlantt"
location.reload(true); // Reloads page
localStorage is persistent, so you can call it on load to fill in the form.
Examples
onload = () => {
if (localStorage.getItem("data")) {
var data = JSON.parse(localStorage.data);
// fill out the form
}
}
And, when someone fills the form, you can save the form data in localStorage.
btn.onclick = () => {
localStorage.setItem("data", JSON.stringify({
// Form data
}));
submitForm(); // The submitting of the form; your code here
}
Note that localStorage can only store strings. So you can convert them to your type.
var number = parseFloat(localStorage.getItem("number"));
var string = localStorage.getItem("string");
var object = JSON.parse(localStorage.getItem("object"));
var array = localStorage.getItem("array").split(",");
var symbol = Symbol(localStorage.getItem("symbol"));
Reference
If you want to learn more about localStorage (and sessionStorage), go to the MDN docs.
You can use the localstorage of the browser (better encrypted). Then, if the user doesen't refresh the localstorage you will be able to use this information to fill the form.

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)

is localstorage also user specific by default?

I am storing some data in the local storage using
localstorage.setItem("key","value")
I understand that localstorage is browser specific, now will this value remain even after i login as different user (sharepoint) in the same browser?
as far as i know localStorage is persistent until user clears it
and i read in this SO question that
Duration
In DOM Storage it is not possible to specify an expiration period for
any of your data. All expiration rules are left up to the user. In the
case of Mozilla, most of those rules are inherited from the
Cookie-related expiration rules. Because of this you can probably
expect most of your DOM Storage data to last at least for a meaningful
amount of time.
So does this mean that local storage is only browser specific? ie even if login as different user in sharepoint, the localstorage values will still remain if i use the same browser? (given that i dont clear it in log out/log in actions in sharepoint)
I understand that localstorage is browser specific, now will this value remain even after i login as different user in the same browser?
Yes.
Definitely.
It has nothing to do with php sessions or the like. Nothing.
LocalStorage is attached to the browser. Log in or log out, has no effect on localStorage.
even if login as different user, the localstorage values will still remain if i use the same browser?
Yes.
You can wrap browser storage with your own interface. It can have expiration by setting a timestamp on writes and checking it on reads.
var Storage = {
get: function (key) {
var item = localStorage.getItem(key)
if (item) {
var entry = JSON.parse(item)
if (entry.expires && Date.now() > entry.expires) {
localStorage.removeItem(key)
} else {
return entry.data
}
}
},
set: function (key, value, expires) {
var entry = { data: value }
if (expires) { entry.expires = expires }
var item = JSON.stringify(entry)
localStorage.setItem(key, item)
},
}

Getting "remember" option to work with Firebase's authAnonymously

I'm trying to use Firebase's anonymous authentication to store data about users who visit my site. But I'm having trouble getting it to work as described.
Here's a simplified snippet of the relevant code:
var firebase_root = new Firebase('https://example.firebaseio.com');
firebase_root.authAnonymously(function(error, authData) {
var page = firebase_root.child(uid).push(); // create a unique reference for this pageload
page.child('loaded_page').set(Firebase.ServerValue.TIMESTAMP);
page.child('left_page').onDisconnect().set(Firebase.ServerValue.TIMESTAMP);
});
In the docs for anonymous authentication, it says
If not specified - or set to default - sessions are persisted for as long as you have configured in the Login & Auth tab of your Firebase's Dashboard.
I've set my Session Length to 12 months in my settings so I would expect that if I load this page and then refresh the page I would get a structure like this:
{
someRandomUserId: {
randomPageId_1: {
loaded_page: timestamp_1,
left_page: timestamp_2
},
randomPageId_2: {
loaded_page: timestamp_3
}
}
}
But it looks like it is actually re-assigning the user ID rather than persisting it across page loads. So I'm actually getting a structure like this:
{
someRandomUserId_1: {
randomPageId_1: {
loaded_page: timestamp_1,
left_page: timestamp_2
}
},
someRandomUserId_2: {
randomPageId_2: {
loaded_page: timestamp_3
}
}
}
Am I doing something wrong or is this a bug?
You're creating a new authentication session each and every time you invoke FirebaseRef.authAnonymously(...). This method only needs to be invoked once, after which the user will authenticated upon page refreshes.
If you'd like to check for the current authentication state of the user, and only then create a new authentication session if the user is not currently authenticated, use the synchronous accessor for authentication state FirebaseRef.getAuth().

What's the best way use caching data in js on client side?

My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.
What's the best solution this problem, using cookie or HTML5
WebStorage?
And may be have other way to solve this task?
As much as cross browser compatibility matters, cookie is the only choice rather than web storage.
But the question really depends on what kind of data you are caching?
For what you are trying, cookie and web-storage might not be needed at all.
Cookies are used to store configuration related information, rather than actual data itself.
Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]
I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.
Update:
Quoting:
data about user activity in some social networks (fb, vk, google+)
Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example
if (Modernizr.localstorage) {
// browser supports local storage
// Use this method
} else {
// browser doesn't support local storage
// Use Cookie Method
}
[1]: http://en.wikipedia.org/wiki/Web_storage
I wrote this lib to solve the same problem:
Cache your data with Javascript using cacheJS
Here are some basic usages
// just add new cache using array as key
cacheJS.set({blogId:1,type:'view'},'<h1>Blog 1</h1>');
cacheJS.set({blogId:1,type:'json'}, jsonData);
// remove cache using key
cacheJS.removeByKey({blogId:1,type:'json'});
// add cache with ttl and contextual key
cacheJS.set({blogId:2,type:'view'},'<h1>Blog 2</h1>', 3600, {author:'hoangnd'});
cacheJS.set({blogId:3,type:'view'},'<h1>Blog 3</h1>', 3600, {author:'hoangnd'});
// remove cache with con textual key
// cache for blog 2 and 3 will be removed
cacheJS.removeByContext({author:'hoangnd'})
Here is an example of caching data from JQuery AJAX. So if you only want to make the call when you don't have the data yet, its really simple. just do this (example). Here we first check if we have the load information (keyed on line, location and shipdate), and only if we dont, we make the AJAX call and put that data into our cache:
var dict = [];
function checkCachedLoadLine(line, location, shipDate, callback) {
var ret = 0;
if(!((line+location+shipDate) in dict)) {
productionLineService.getProductionLoadLine(line, location, shipDate, callback);
}
return dict[line+location+shipDate];
}
...then in the call back write the value to the cache
function callback(data) {
if (!data) {
document.getElementById('htmlid').innerHTML = 'N/A';
} else {
document.getElementById('htmlid').innerHTML = data[0];
dict[data[2]+data[3]+data[4]] = data[0];
}
}

Categories