Remembering user action using cookies - javascript

I'm working on a "this site uses cookies" message to show the user when they go on the index page of the site.
I want the user to be able to dismiss the message, and the browser should remember, so it isn't displayed again when the user reloads the page.
I'm using Laravel, and I've looked into storing variables in the session,
but the request doesn't go through a controller to get to the index view.
When the user clicks the button, the message should disappear without reloading.

This can be done only with Javascript, without going over the server, in the onclick event of your button, call a function with code of creating a cookie or storing a value in Localstorage of the browser :
Code to create cookie with JS :
document.cookie = "accept=true";
Code to create value in localStorage :
localStorage.setItem('accept', 'true');
And then try to get the value from cookie or local storage like this :
Cookies :
var x = document.cookie;
//document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;
LocalStorage :
var accept = window.localStorage.getItem('accept');
if(!accept)
{
....................
}

Related

my code storage data in local storage on a website but when i navigate through the pages and register a new user the old user are deleted

var userInfo = [];
var myCostum;
//documentgetElementById("registerForm");
document.getElementById("registerForm").addEventListener("click", function ()
{
//var register = document.querySelector('#registerForm');
var name = document.querySelector('#fN').value;
var lastN = document.querySelector('#lN').value;
var userName = document.querySelector('#uN').value;
var passwrd = document.querySelector('#pS').value;
userInfo.push([name,lastN,userName,passwrd]);
localStorage.setItem("myCostum", JSON.stringify(userInfo));
});
I am using separate files for j, my website has a navigation bar with home,register,login,about me and shopping car. this code works fine if i register more than one user, i can see the users in the local storage on all pages and i can even sign in. the problem is when i go to register again and register a new user the users that i reister before are deleted and replaced by the new user. also if i go to home page i can an error (Uncaught TypeError: Cannot read property 'addEventListener' of null
at even-listener.js:9). i just do not had idea why register page seems to work but the rest not. I had another code using onclick in html but the same it does not give any error in any page but the users gone when i register new one after navigating through my pages. this is the first time using localStorage and i do not can i do or if it is normal. i am stack and i need to keep adding more code but i want to solve this problem first.
Lots of things going on here, but let me start from the basics.
1st never use local storage for sensitive information such as usernames and passwords. There's a lot of sites that copy local storages and send it to malicious people.
2nd you could in theory use session storage limited to the tab, but you still could be under the danger of xss.
3rd when the browser closes, all your data will be lost from the local storage anyway
As for your code. Your user info, should not be initiated as empty. You must get the previous value from local storage and push to it. Otherwise you are just overriding the previous value.
var userInfo = JSON.parse(localStorage.getItem('myCustom'));

Storing session landing page in cookie for form parsing (via hidden field)

I am looking to pass through the landing page URL of a session as a hidden field in a site's contact form. This is ideal for salespeople so they can see the intent of the user etc.
I have successfully passed through Google Analytics values as hidden fields from the _utmz cookie set by GA.js, but am unable to extract the session langing page.
With this in mind I can see it is necessary to then store the first page of the session into cookie which could then be read and extracted into hidden field on the form.
The logic I am looking to follow would be as follows:
if cookie 'landing_page_url' does NOT exist, set 'landing_page_url' to document.URL
else do nothing
then on the form pass the stored value for 'landing_page_url' into the hidden field 'landing page'
Would this be possible with javascript, and any ideas about an easy way to implement?
I would suggest using the localStorage: To store your value use localStorage.setItem (yourVariableName, theValueYouAreStoring);. To retrieve your value use var theValueYouAreStoring = localStorage.getItem (yourVariableName).
Alternatively, you can use a cookie. To write one use document.cookie = 'cookieName=yourValue; expires=Session; path=/';
To retrieve your cookie use var cookiePlace = document.cookie.indexOf (cookieName + '=') + cookieName.length + 1; var yourValue = document.cookie.substring (cookiePlace);

Javascript > form results to "remember" user > avoid showing form twice

I have a java script form in a website, that outputs some results -a silly simple mathematical operation or subtraction of dates.
I need these results to "remember" the visit so the div and the results
show when the user re-loads the page.
How can I achieve this?? It's my first time with facing a situation like this...
Note: its not a logged user!! but a non-logged visit..
http://goo.gl/OHQmpb
You can use localStorage.
Store the values in it by specifiying a key:
localStorage.setItem('key','value');
And, you can get the value by:
var value = localStorage.getItem('key');
HTML5 Web storage is the best option in your case.
Exact definition:
So what is HTML5 Storage? Simply put, it’s a way for web pages to
store named key/value pairs locally, within the client web browser.
Like cookies, this data persists even after you navigate away from the
web site, close your browser tab, exit your browser, or what have you.
Unlike cookies, this data is never transmitted to the remote web
server (unless you go out of your way to send it manually).
With HTML5, web pages can store data locally within the user's browser.
// Store it in object
localStorage.setItem("form attributes", "form values");
// Retrieve from object
localStorage.getItem("form attributes");
HTML5 Local Storage aka Web Storage can store values without maintaining a server side session. See this example:
function calculate(){
return 'some value';
}
window.onload = function(){
// submit handler for the form, store in local storage
document.getElementById("myform").onsubmit = function(){
localStorage.setItem('calcResult', calculate());
return false;
};
// load the value if present
var result = localStorage.getItem('calcResult');
if(result != null){
// show in div
document.getElementById("mydiv").innerHTML = result;
}
}

How to prevent the loss of form data when session expires?

QUESTION
Using ASP.NET VB and/or JavaScript how can a user be prevented from losing form data when a session expires?
The Problem
Currently when a user is filling out form data for a period longer than the session timeout period all form data is lost on post due to session expiry.
Client side actions such as typing DO NOT reset the session timeout period.
Ideas
I would like to know ways to prevent this problem occurring.
My initial idea is a notification message warning of pending expiry
and an option to reset session timer.
An alternate idea is a way to pass a key press or mouse movement to the server to cause an auto refresh of session timer.
SOLUTION 1 : KEEP SESSION ALIVE
On way of to solve your problem is to keep session alive while the form is opened. I'm sure there many ways to 'keep alive' user's session. For me, I use generic handler and this work fine at least in my requirement.
First, create a generic handler and enter code as below:
Public Class KeepSessionAlive
Implements IHttpHandler, IRequiresSessionState
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
context.Session("KeepSessionAlive") = DateTime.Now
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Make sure your generic handler class implements IRequiresSessionState as above.
Then in you form page, use jQuery.post to post request the above handler at time interval of you choice. For example:
<script type="text/javascript">
$(function () {
setInterval(function () { $.post('<%= ResolveClientUrl("~/KeepSessionAlive.ashx")%>'); }, 10000); ' 10 secs interval
});
</script>
While user is on the form, the POST requests will keep refreshing user's session just like normal page requests and therefore, IIS will keep on reseting the session timeout.
SOLUTION 2 : ALERT USER BEFORE TIMEOUT
Another way is to alert user when session is about to end. This can be achieved simply by using plain javascript alone. I used this method few years back so pardon my scripting.
Create a javascript method :
function sessionTimeout(n) {
setTimeout("alertSessionTimeout()", (n - 1) * 60 * 1000);
}
function alertSessionTimeout() {
var answer = confirm("Your session is about to expire in 1 minute.\n\n
Click 'OK' to extend your session.\n
Click 'Cancel' to terminate you session immediately.");
if (answer == true)
window.location = location.href;
else {
window.top.location = 'logout.aspx';
}
}
On your form page, just enter onload script on your body tag:
<body onload="sessionTimeout(<%=session.Timeout %>)">
So, if your timeout setting is 10 minutes, user will be alerted on the 9th minute. Of course, you might want to change the code when user click OK button. My code above will refresh the page and that definitely not what you want to do, or else, user's data will be lost. You can use the generic handler as in SOLUTION 1 above to reset the session and call sessionTimeout again to reset client side timeout countdown.
In the age of single page apps if you need to work with old school approach, my advise would be to create Ajax request that constantly updates data in your website or just checks for session expiration (probably request itself would prevent that). But if it happens and you receive session expired message you could just show some login popup for user to login without leaving actual page.

Detecting Unique Browser Tabs

On every page of my sites, I am using AJAX to poll the server and retrieve a list of messages. The server maintains a list of messages and the SessionId (I'm in an ASP.NET environment, but I feel like this question is applicable to any server side technology) that the message is intended for. If a message is found for the particular SessionId, it is returned to the client side script. I use a JavaScript library to create a notification (using noty, a Jquery Notification Plugin). Once it returns a particular message, the server discards that message.
This works well if the user only has a single tab/window open for a particular site. However, let's say they have two open and they do something that causes a warning message to be generated. I have no control over which tab the notification goes to, so the user may not end up seeing the warning message.
Is there a way of uniquely identifying a browser tab? Then I could pass this as one of the parameters in my AJAX call.
Firstly, polling doesn't seem good mechanism. It might hit your server down when you have large number of active users. Ideally you should return a message in the response to the request that was result of invalid action.
Still below solution might work for you. It is inspired by the reply of #SergioGarcia.
Keep a hidden input just before the end of your form tag, which stores a unique ID for identifying a tab uniquely. You will store the messages on server session against unique tabID,
<input type="hidden" id="hiddenInputTabId" value="<%=getValue()%>" />
and then define getValue.
function string getValue() {
var v = getValueFormBodyOrAccessValueDirectlyByMakingInput_a_ServerSideControl();
if (string.IsNullOrWhiteSpace(v)) {
return Guid.NewId();
} else {
return v;
}
}
Because it is a hidden input you should get it's value in the POSTed form body, and for ajax requests below snippet should take care of sending that value in header which you can access on server side.
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader("tabId", $('#hiddenInputTabId').val());
},
});
Same header can be check while returning the response to your polling requests and only respond message available against the provided tabId should be responded.
You can add a query string parameter called tabId and control it's binding to tab using javascript.
There is a functional prototype below:
$(function () {
// from: https://developer.mozilla.org/en-US/docs/Web/API/Window.location
function getQueryStringParameter (sVar) {
return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
// from: http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
function newGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
}
window.tabId = getQueryStringParameter('tabId');
// tabId not defined, reload the page setting it
if (!window.tabId) {
window.tabId = newGuid();
}
// on click set the tabId of each link to current page
$(document).on('click', 'a', function (e) {
var $this = $(this);
var newLocation = $(this).attr("href");
// In page links
if (newLocation.match(/^#.+$/)) {
return;
}
// Outbound links
if (newLocation.match(new RegExp("^https?")) && !newLocation.match(new RegExp("^https?://" + window.location.host))) {
return;
}
// Insert tab id
if (newLocation.match(/(\?|&)tabId=[0-9a-f-]+/)) {
newLocation.replace(/(\?|&)tabId=[0-9a-f-]+/, (newLocation.indexOf('?') == -1 ? "?" : "&") + "tabId=" + window.tabId);
} else {
newLocation += (newLocation.indexOf('?') == -1 ? "?" : "&") + "tabId=" + window.tabId;
}
window.location.href = newLocation;
e.preventDefault();
});
});
If you enter a page in your application without setting the tabId parameter on query string, it will be set to a new UUID (Guid).
When the page has a tabId parameter on query string, it defines the window.tabId variable inside your page and you can use that in your application.
When the user click on any link in your page, a javascript event will be triggered and the link url will be redirected to match the current tabId. An right click to open in new tab or a middle click will not trigger that event and the user will be sent to a new tab without the query string parameters, so the new page will create a new tabId in that page.
You can see it working here: http://codepen.io/anon/pen/sCcvK
You can do it by generating a unique tab id with javascript by loading your client.
I strongly recommend you to use something for intertab communication, like intercom.js, which can broadcast the messages from a single tab with a single connection to every other tabs. Intertab works with socket.io, which has long polling fallback, so it may be good in your current system as well. I agree that polling is a poor choice, and you should use websockets instead.
If you use ZMQ on the server, then in the browser you can use NullMQ either (for websockets ofc). I think it does not have intertab support, so you should make your own intertab solution to make it work. It is not so hard to write such a system, you need only a common storage, for example localStorage, but it can be even cookie... If you don't have a storage event, you have to ping that storage for changes with setInterval. You have to store there the messages, and which tab broadcasts them (probably in a semaphore) and when was the last time it pinged the storage. After that you can keep each tab in sync with the others, or by using a unique tab id, you can send customized messages to any of the tabs. If the broadcast tab has a storage timeout (it did not ping the storage for a long while), then it is probably closed, so you should assign the broadcast service to another tab.
So what I ended up doing was changing how my notification framework functioned in order to prevent the need for identifying unique tabs. It's just too hard to layer information on the stateless web.
Instead of using Ajax to pump messages out to the client instantly, I build them up on each page into a List<Message> property. On PreRender I render them to the client with ClientScript.RegisterStartupScript(). But if I need to send the user to another page, I started using Server.Transfer() instead of Response.Redirect() instead so that it will preserve the message queue. The new page checks the old page to see if it exists and if is the correct Type. If it is the correct type, I cast it and retrieve the message queue from the old page and add them to the new page's queue. And since Server.Transfer() doesn't update the URL on the client, I also added a JavaScript function to manually push the state to the URL in supported browsers.
I know I took this in a little different direction than I did on the question, but I think I had been approaching it wrong in the beginning.

Categories

Resources