getting or setting cookies with javascript - javascript

My question is if I can set a cookie using javascript (and read it)
My first impression is that the code beneath doesn't work
If I look in my vista cookie folder, I can not see the name of the cookie
function zetCookie(naam,waarde,dagen) { // setCookie(name,value,days)
if (dagen) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var verloopdatum = "; expires="+date.toGMTString(); // expiry_date
}
else var verloopdatum = "";
document.cookie = naam+"="+waarde+verloopdatum+"; 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;
}

I can't answer why the cookie is not showing in your Vista folder, but that code properly sets and reads cookies as intended. How are you testing it? An easier way to test whether the cookies are sticking is by simply doing something like this:
<input type="button" value="Set" onClick="createCookie('test','yay',5);">
<input type="button" value="Read" onClick="alert(readCookie('test'));">
You can refresh the page between Setting and Reading it if makes you feel better, but it works for me.
If that doesn't show what you're expecting, make sure your browser is setup to accept cookies. :)
EDIT: Looking at your code, you missed replacing days in this line:
date.setTime(date.getTime()+(days*24*60*60*1000));

I'm testing it here: http://flamencopeko.net/cookie.php and here: http://flamencopeko.net/cookie.js. Works perfect.
And, yeah, Firebug's Cookies panel is great.
I'm trying to use your script to save font size preference. Here is a thread on that: simplify font size toggle.

Install Firefox
Install FireBug
Install FireCookies
Download JQuery
Download the Cookie plugin

Related

How can I show popup with slimbox on page load only for the first visit?

So far my idea was to implement a function popup("url") checking for an existing cookie which is triggered by loading the body of the page (onLoad - not a nice solution I know). I used the exact code from here to implement cookie functionality which I included in my application.js . There I also included my popup() function:
function popUp(startimage) {
var x = readCookie('ecocrowd')
if (x = 'nopopup') {
}
else {
jQuery.slimbox(startimage);
}
}
In the html-template for my start page I included the following parts:
<body onLoad="popup("wirdiezukunft.png")">
and
<script>createCookie('ecocrowd','nopopup',7)</script>
Am I missing something out? It is the first time I am working with a Javascript implementation like this so I would appreciate any kind of help. Thanks in advance!
update (content of createcookie() ):
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
Forget cookies, use localStorage as it has a much more practical interface, and no weird stuff with paths, expirations and domains:
if(!window.localStorage.getItem('hasShown')) {
showMyPopup();
window.localStorage.setItem('hasShown', true);
}
There is actually a much more practical interface for cookies in HTML5 but it isn't as widely supported as localStorage yet.

JavaScript: Saving/Loading cookies using HTML documents for a website

For school work I need to use JavaScript to Save and read a cookie. The code for setting the cookie is all good, I got it from w3Schools (I know it's a terrible guide apparently). My problem is getting it to work with HTML/notepad using the "path" thing going on.
When the webpage loads a function called checkcookie checks if the cookie exists, if it doesn't, it asks the user to enter their name and then saves a cookie for later. If a cookie already exists, it displays a greeting message :). So far, I have made the functions work on the example running interface thing that you can access on w3schools. However, I recently tried setting them up using HTML documents, and the cookies don't seem to save properly. I open a NotePad document, paste the code, save as HTML, and open with Google Chrome. The pop-up asks for my name, I enter, but when I reload, the pop-up asks for my name again, and again, and so on. Here is the page I got the functions from: http://www.w3schools.com/js/js_cookies.asp
I think I need to sort out a path for the cookie, or something, I looked at this webpage for more info http://www.quirksmode.org/js/cookies.html but I still don't understand.
Why does this not work? Should I set the path to the file directory which the webpage's html documents are saved in? Why does it work in the w3schools TryIt system but not with raw HTML documents?
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires+"; path=/";
}
function getCookie(cname) {
var title = cname + "=";
var cookie_array = document.cookie.split(';');
for(var i=0; i<cookie_array.length; i++) {
var check = cookie_array[i];
while (check.charAt(0)==' ') check = check.substring(1);
if (check.indexOf(title) != -1) {
return check.substring(title.length, check.length);
}
}
return "";
}
function checkCookie() {
var name=getCookie("name");
if (name != "") {
alert("Welcome again " + name);
} else {
name = prompt("Please enter your name:","");
if (name != null && name != "") {
setCookie("name", name, 30);
}
}
}
Yep, as mentioned by jyrkim is a webserver thing

javascript - read a seperate tab to check if it's open

I'm looking for a way to somehow read / check if another browser tab is open before opening the requested tab.
For example:
This is for my traffic exchange site, they just open mysite.com/surf.php and leave it viewing user's submitted sites in a frame. They earn points just for leaving that running.
Now lets say USER A has SURF PAGE A running fine and then opens SURF PAGE B then he has 2 mysite.com/surf.php running and earning double the points everybody else will earn.
What I want to happen is:
USER A has SURF PAGE A running fine and then tries to open SURF PAGE B which will check if another mysite.com/surf.php is already open and if it is to redirect the request for the 2nd surf page to another mysite.com/surf-error.php
So they can only ever have 1 mysite.com/surf.php running at any given time.
How would I go about doing this?
Browser windows on the same domain in the same browser can exchange some information via:
Cookies
Local Storage
Communication with a common server
You can use 1) or 2) to store some information about an active page and refuse to let other pages be active if one is already active.
But, the most reliable way to enforce policies like you are asking about is to use the actual server to enforce it. If users have a login, then code the server to only allow a logged in user to accumulate points for one site at a time.
Other than these options, if you want to enforce it all client-side, you would probably need a browser-plugin that could monitor all open browser windows (which I assume is not practical). You cannot do monitoring of multiple windows opened by the user from plain javascript in a web page.
when you start tracking time for someone set a session variable
session.trackingtime = true
when you check again to start tracking time make sure that value is set to false. When you stop tracking time set the variables to false.
I have done something very similar today. Just update the else if part to do a redirect in your case.
// helper function to set cookies
function setCookie(cname, cvalue, seconds) {
var d = new Date();
d.setTime(d.getTime() + (seconds * 1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
// helper function to get a cookie
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.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 "";
}
// Do not allow multiple call center tabs
if (~window.location.hash.indexOf('#admin/callcenter')) {
$(window).on('beforeunload onbeforeunload', function(){
document.cookie = 'ic_window_id=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
});
function validateCallCenterTab() {
var win_id_cookie_duration = 10; // in seconds
if (!window.name) {
window.name = Math.random().toString();
}
if (!getCookie('ic_window_id') || window.name === getCookie('ic_window_id')) {
// This means they are using just one tab. Set/clobber the cookie to prolong the tab's validity.
setCookie('ic_window_id', window.name, win_id_cookie_duration);
} else if (getCookie('ic_window_id') !== window.name) {
// this means another browser tab is open, alert them to close the tabs until there is only one remaining
var message = 'You cannot have this website open in multiple tabs. ' +
'Please close them until there is only one remaining. Thanks!';
$('html').html(message);
clearInterval(callCenterInterval);
throw 'Multiple call center tabs error. Program terminating.';
}
}
callCenterInterval = setInterval(validateCallCenterTab, 3000);
}

load an ad (div) just once on first load

I wanted to know how can I have a div that has an ad to load or become visible ONLY the first time you load the page but hide it every time the page is refreshed?
I only have the code to load the div with Jquery but don't know how to hide it after refreshing the page:
$(document).ready(function() {
$(".referralProgram").fadeIn("slow");
});
Use a cookie:
$(document).ready(function() {
if (!readCookie("adSeen")) {
$(".referralProgram").fadeIn("slow");
createCookie("adSeen", "1", 1000);
}
});
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
} else var expires = "";
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;
}
Cookie functions from quirksmode.org.
Edit: Since so many are discussing how to deal with this if cookies are disabled, it should be pointed out that server session implementations rely on either a cookie, or a session identifier in the url. At best, you could only prevent displaying the ad for the same user as long as the session identifier is in the url. Returning to the home page sans session id would re-display the ad. Additionally, a careless implementation (and even some careful implementations) could result in false positives for other users if a user shares a url. localStorage solutions won't work with cookies disabled in most, if not all, browsers.
You'll need a way to keep track of when an ad has been displayed to the user. Set a cookie when the ad is created and check for it before displaying again?
You can use client side persistent storage to flag the user has already seen this. Here are 3 options:
1) Cookies - Set a cookie on the visiting users machine.
2) HTML5 Storage - You can store the flag in browser (HTML5 Only) storage.
3) Server Session - If you are using middleware (PHP, ASP.NET, Java, etc.) you can track via a session variable (this is an abstraction of a cookie and is only as persistent as you create it to be).
I am not sure what your server side implementation is like, but if you are worried about cookies being turned off you could handle this on the server side using session state.

Accessing cookies, hopefully in JavaScript

I am working on a Firefox add-on that will allow users (all of whom are part of a specific group; this add-on is very limited in audience scope) to see the status of their authentication cookie from the status bar. We all have to authenticate to access work-related sites, but we get no warning when the cookie expires, so this causes annoying and sometimes drastic interrupts in work flow. Eventually, this add on will allow us to submit our credentials from the status bar without having to go to do any reloads or redirects, but for now, I just want to see it show the status.
I have been looking at the Mozilla developer pages at nsICookie, nsICookie2, nsICookieManager, etc, and it doesn't make very clear sense how any of it fits into JavaScript or XUL or anything else.
Ideally, I'd just like a way for the JavaScript to go outside of the document and get the cookie string for a domain I specify. If I could do that, it would allow the code to possibly be ported over to other browsers (Safari and Chrome, in particular). But if this must be browser specific, then I would at least like to know the method for checking if the cookie exists in Firefox without any bells and whistles of setting or removing.
Simply put, I want a way to say:
if (cookieExists("sample.com", CookieName)) {
alert("You're signed in!");
} else {
alert('Go sign in, you fool!');
}
What is the easiest/most portable way of doing this (browser-side, of course)?
I have been looking at the Mozilla developer pages at nsICookie, nsICookie2, nsICookieManager, etc, and it doesn't make very clear sense how any of it fits into javascript or XUL or anything else.
access to all cookies from Firefox extension is possible and uses the nsICookieManager and nsICookie interfaces. From javascript code in your extension, you access the cookie manager with
var cookieManager = Components.classes["#mozilla.org/cookiemanager;1"].getService(Components.interfaces.nsICookieManager);
and than you can iterate through all stored cookies
var enum = cookieManager.enumerator;
while (enum.hasMoreElements()){
var cookie = enum.getNext();
if (cookie instanceof Components.interfaces.nsICookie){
// commands
}
}
now, when having reference to cookie object you can check its properties
cookie.host
cookie.name
cookie.value
...
defined in nsICookie interface. This code is Firefox specific and can be run as a browser extension or signed script. Hope my explanation helped a bit.
Below I present some links on using JS XPCOM interfaces in extensions:
JS XPCOM
Using cookies
you can use jquery plugin for cookie handling
http://www.stilbuero.de/2006/09/17/cookie-plugin-for-jquery/
or simply through javascript :
http://www.quirksmode.org/js/cookies.html
Here's a nice tutorial for working with cookies in javascript. Using the functions from that tutorial, you could probably do something like this:
if readCookie(yourCookieName != "") {
alert("You're signed in!");
else {
alert("Go sign in, you fool!");
}
Here are the cookie functions:
function readCookie(name) {
var ca = document.cookie.split(';');
var nameEQ = name + "=";
for(var i=0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return "";
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function eraseCookie(name) {
createCookie(name, "", -1);
}

Categories

Resources