I wanted to create a logout feature by deleting the cookie on the client side. But don't know how to do it
so far this code is not working.
Any help would be appreciated
<script>
function clearCookie(name, domain, path) {
var name = "yoursite.com"
var domain = ".yoursite.com";
var path = "/";
document.cookie = name + "=; expires=" + +new Date + "; domain=" + domain + "; path=" + path;
};
Here is an article from Coder Rocket Fuel
How to Create, Read, Update, & Delete Cookies in JavaScript
This is some C# I had...it should translate easily.
Again...you set the expiration in the past.
protected void CreateCookie(string location)
{
HttpCookie httpCookie = new HttpCookie("Location", location);
httpCookie.Expires = DateTime.Now.AddYears(10);
Response.Cookies.Add(httpCookie);
}
protected void DeleteCookie()
{
HttpCookie httpCookie = new HttpCookie("Location");
httpCookie.Expires = DateTime.Now.AddSeconds(-1);
Response.Cookies.Add(httpCookie);
}
Related
We are using jsxc javascript client to access openfire chat server. However we have problems loading the chat history.
The history is stored in the database, we just do not know, how to retrieve it.
var url = 'servername';
var domain = 'https://' + url + ':7443/http-bind/';
var sid = jsxc.storage.getItem('sid');
if (sid == null) sid = username;
jsxc.init({
xmpp: {
url: 'https://' + url + ':7443/http-bind/',
sid: sid
},
root: '/jsxc'
});
var jid = username + '#' + url;
jsxc.start(jid , password);
This is our initialization script. Do we have to add something else?
Best,
Bojan
I have a situation in my application where the users should are not allowed to open multiple instances of the application in a browser. So we are reading the cookies, if there is a session already opened we alerting the user that they are attempting to open multiple sessions.Some times if the browser crashes for some reason the browser is still having the old cookie and when the user is attempting to open the application again the browser is not allowing the user to login. User has to manually delete the cookie from the browser history. The business doesn't want that process.FYI I am using angularJS
Found the same question in other post but didn't find an answer I want here Can someone please help me out with this. Thanks in advance!
I came up with the following code. But when the application crashes the cookie is still sitting in the browser and not allowing the user to login at all. The only workaround for me now is to delete the cookie manually from the browser and login.
var duplicateApp = false;
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
window.onload = function(){
var MyAppCount=readCookie("MyApp");
if (MyAppCount > 0) {
duplicateApp = true;
alert("You are attempting to open multiple application sessions.\n\nPlease close any existing application from the web browser before restarting the application.");
var win = window.open("about:blank", "_self"); win.close();
}
else {
duplicateApp = false;
createCookie("MyApp", 1, 1);
window.onunload = function(){
if (duplicateApp == false) eraseCookie("MyApp");
};
}
};
Could you please suggest any changes I have to make to restrict the user to open only single instance of the application.
I would typically handle this on the login page by creating a new session and invalidating the old one when a user logs in again with the correct credentials.
I have an application that needs to pop a URL based on a Query String sent to it. Unfortunately, we can't insert any javascript into the application itself, but we can insert an iFrame that loads a page running javascript. There is a bug in the application where it loads the content in the iFrame twice within a couple seconds, which results in the URL popping twice.
To resolve this, I decided to set a cookie with an expiration. Before popping, I would check to see if the cookie exists, and if it does, prevent the pop from happening.
Unfortunately, my cookie is not being set. I've read a few threads about Javascript cookies trying to figure this out. The first thing I found is Chrome does not accept cookies from local files, so I set up an IIS server to host the page.
However, the cookie still is not being set. I read this page to make sure my code was correct, and as far as I can tell, it should be correct.
The code for my page is below. Any help would be greatly appreciated.
<html>
<head>
<script type="text/javascript">
var isPopped;
function myFunction() {
alert("Hello! I am an alert box!");
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
function pop() {
var queryString = location.search.substring(1); //Get Query String from URL of iFrame source. The substring(1) strips off the ? and only takes the first substring. This can be modified to take more and the resulting string can be edited with Regular Expressions if more flexibility is required.
var urlToPop = "https://www.google.com/#" + queryString //Set URL to pop.
var recentVisitTrue=getCookie("visitRecent");
if (recentVisitTrue != "") {
isPopped = 1;
} else {
window.open(urlToPop,"_blank");
setCookie("visitRecent", "true");
}
}
function setCookie(cName,cValue) {
var date = new Date();
date.setTime(d.getTime() + 8000000);
var expires = "; expires=" + date.toGMTString();
document.cookie = cName + "=" + cValue + expires + ";path=/";
}
function getCookie(cName) {
var name = cName + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
</script>
</head>
<body onload="pop();">
v0.32
</body>
</html>
Thanks!
In my Javascript I have a cookie with several names and values:
"Token=23432112233299; sessionuid=abce32343234"
From server when I download a file a Add a Cookie so the new document cookie will look:
"Token=23432112233299; sessionuid=abce32343234; fileDownload=true"
How can I remove the fileDownload name and value from cookie and update document.cookie?
UPDATE:
This is the code I have done so far but its not working:
if (document.cookie.indexOf("fileDownload=true;") != -1) {
document.cookie = document.cookie.replace("fileDownload=true;", "");
} else {
document.cookie = document.cookie.replace("fileDownload=true", "");
}
Change the expires parameter to the elapsed date.
document.cookie = 'fileDownload = ; expires=-1';
var cookieData = "fileDownload=; path=/" +"; expires=" + new Date(0).toUTCString() + ";";
if (null) cookieData += " domain=null;";
document.cookie = cookieData;
I'm trying to do a demo test on javascript cookie. Please find the code below which I wrote for testing.
<html>
<head>
<script type='text/javascript' >
function setcookie()
{
alert("check if cookie avail:" +document.cookie.split(';'));
var dt=new Date();
document.cookie='name=test';
document.cookie='expires='+dt.toUTCString()+';'
alert("now cookie val:" +document.cookie.split(';'));
dt.setDate(dt.getDate()-1);
document.cookie = "expires=" + dt.toUTCString() + ";"
alert("after deletion cookie val:" + document.cookie.split(';'));
}
</script>
</head>
<body>
<input id='txt' onchange='setcookie()' />
</body>
</html>
The code will work as,
Initally, this will display the cookie which is present already in that browser, then I try to set a cookie as 'name=test' with 1day expire time. Using alert I can see the value set in that cookie. In the next line, I try to delete cookie by setting expire date to current date-1. If I use alert to print the cookie value, cookie is displayed with expire date as currentdate-1.
My questions is,
In Mozilla, If I refresh the browser and try to do the same step then the first alert displays the cookie value with expire time as currentdate-1. Why Im getting cookie value even if i delete at the last line of my script. However, once I close the browser the cookie value is empty. Why it is so?
In chrome, If I run the same piece of code, neither of the cookie is set. Why Im not able to set cookie in chrome browsers.
Please tel me why such difference occuring across browsers.
This is not setting the expiry
document.cookie='name=test';
document.cookie='expires='+dt.toUTCString()+';'
this is
document.cookie='name=test; expires='+dt.toUTCString()+';'
The best is to take well tested cookie code and use that
Try this one or use a jQuery plugin if you use jQuery
// cookie.js file
var daysToKeep = 14; // default cookie life...
var today = new Date();
var expiryDate = new Date(today.getTime() + (daysToKeep * 86400000));
/* Cookie functions originally by Bill Dortsch */
function setCookie (name,value,expires,path,theDomain,secure) {
value = escape(value);
var theCookie = name + "=" + value +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((theDomain) ? "; domain=" + theDomain : "") +
((secure) ? "; secure" : "");
document.cookie = theCookie;
}
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
var offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
var end = document.cookie.indexOf(";", offset)
// set index of end of cookie value
if (end == -1) end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
function delCookie(name,path,domain) {
if (getCookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-70 00:00:01 GMT";
}