Read a cookie when implementing inside of another function - javascript

I have the following function to change stylesheets on my website that I want to use cookies to keep stylesheet theme persistent across pages.
<script type="text/javascript">
var i=1;
function styleSheet(){
if(i%2==0){
swapper('css/main.css');
document.cookie = "username=Visitor";
}
else{
swapper('css/stylesheetalternate.css');
document.cookie = "username=alternateVisitor";
}
i++;
}
<button onclick="styleSheet()">Click me</button>
I'm already setting my cookies inside of this function. I'm not too interested in setting expiration dates or anything like that, the default is fine for me. What I do want to try doing however is read the cookies inside of this function each time that I use the button I created. Is there no way to read it inside of the same function?
I'm aware that there exists a jquery library that does this, but I don't want to use jquery if I can get a better performance with javascript.
EDIT:
<script type="text/javascript">
var i=1;
function styleSheet(){
if(i%2==0){
swapper('css/main.css');
document.cookie = "username=Visitor";
readCookie(Visitor);
}
else{
swapper('css/stylesheetalternate.css');
document.cookie = "username=alternateVisitor";
readCookie(alternateVisitor);
}
i++;
}
Do you mean something like the following when you say to use readCookie inside of my function? What I notice from this sort of implementation is that after swapping stylesheets once, it is for whatever reason impossible to swap again until the page is reloaded.

Here's a set of plain javascript cookie functions that you can use from any function. So, to your question, you can call readCookie("username") from your function (or read any other cookie value):
// createCookie()
// name and value are strings
// days is the number of days until cookie expiration
// path is optional and should start with a leading "/"
// and can limit which pages on your site can
// read the cookie.
// By default, all pages on the site can read
// the cookie if path is not specified
function createCookie(name, value, days, path) {
var date, expires = "";
path = path || "/";
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=" + 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);
}

document.cookies is just a big list of all the cookies. You can parse through it to find the one you're interested in:
function getCookieValue(cookieName) {
var value = null;
document.cookie.split(';')
.forEach(function(pair){
var pairArray = pair.split('=');
if (pairArray[0]==cookieName) {
value = pairArray[1];
}
});
return value;
}
(Untested, let me know how it goes.)

Related

Show different HTML code after one visit

Only using Javascript, can someone create a html file that uses "XY" html code when the user first visits it, but it should use "ZQ" (so a fully other one) html code after the first visit? So in the second, third, etc. visit of the same user. There could be many users.
Question: how would that html file look like? How to do it? Is it possible using only javascript?
You can use either Cookies or LocalStorage, where the LocalStorage is easier to implement, but requires the latest browser, and users may disable cookies for privacy reasons.
Cookies
function setCookie(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 getCookie(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;
}
// First Visit
if (getCookie("visited") == null) {
// XY code.
alert("XY Code here");
// set the cookie
setCookie("visited", "yes", 10);
} else {
// subsequent visit.
// ZQ code.
alert("ZQ Code here");
}
LocalStorage
if (typeof(Storage) !== "undefined") {
if (localStorage.getItem("visited") == "yes") {
// subsequent visit.
// ZQ code.
alert("ZQ Code here");
} else {
// XY code.
alert("XY Code here");
// set the cookie
localStorage.setItem("visited", "yes");
}
} else {
// Sorry! No Web Storage support..
// Use the above cookie method.
}

Setting Cookie Expiration time.

I have the following script that is for a popup on my home page. It works well except the cookie seems to reset its self every day. I would like for the cookie to expire as far into the future as possible. My problem is that i am new to javascript and cookies within. Can someone let me know what part i need to change? I have messed with some of it but seem to be making it worse.
As it sits on my site (http://www.swissdiamond.us) You can see that it is working (loads the div the first time you are there, and not any other) but if you come back tomorrow the hidden div will re-load.
Thanks for any help
<script type="text/javascript">
//<![CDATA[
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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
function showModal() {
tb_show('Newsletter Signup','#TB_inline?height=300&width=450&inlineId=promo',false);
}
var visited = readCookie('mypopup');
if (!visited) {
$(document).ready(function(){
showModal();
createCookie('mypopup','no',0);
});
}
//]]>
</script>
You need to update this line
date.setTime(date.getTime()+(days*24*60*60*1000));
Or you can pass days value from here
createCookie('mypopup','no',0); // make the last parameter value as much as you want
Here you can add more days as you want. hope this helps.
Your createCookie function sets the expiry for you, however you are passing 0 as the days value to expire, so the cookie does not persist. Try this:
createCookie('mypopup', 'no', 7); // 7 = expires in 7 days, amend as required.

Cookie Detection , Redirect if Non javascript

Tying to write a JavaScript code that will detect if a user has cookies disabled in their browser. If they do, they will be redirected to another page. If they have their cookies enabled it just goes straight through as usual.
i have a code that already works but it still hits the page for a split second before redirection. Is there anyway to make it instant.An example of fast detection is here ( try it with cookies disabled) http://optusnet.com.au
You will see it is instant and doesn't load the page request first.
<script type="text/javascript">
/* function to create cookie #param name of the cookie #param value of the cookie #param validity of the cookie */
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.toGMTString();
}
else
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;
}
function eraseCookie(name)
{
createCookie(name, "", -1);
}
/* This function will create a new cookie and reading the same cookie. */
function areCookiesEnabled()
{
var r = false;
createCookie("testing", "Hello", 1);
//creating new cookie
if (readCookie("testing") != null)
{
//reading previously created
cookie r = true;
eraseCookie("testing");
}
return r; //true if cookie enabled.
}
</script>
<script>
if(!areCookiesEnabled())
{
//redirect to page
}
</script>
You won't be able to make it "instant" with client-side code (i.e. JavaScript) because the page has to be loaded for this code to run. You can achieve this with server-side code, however (like the page you link to does). Here's what you'd have to do, in whatever your server-side language is:
On the load of your first page, set a cookie and immediately send a redirect instruction to your main page.
On your main page load, check for the cookie. If no cookie exists, cookies are disabled, so redirect to a third (error) page.
If the cookie exists, allow the page to load normally.
Alternatively, you can try making it faster by reducing the number of HTTP requests required for your "checking" page (i.e. don't include any styles, etc. on the first page and then redirect to a "proper" page if the test passes) and using more efficient detection methods as per Joe's comment; however, you won't be able to implement an immediate redirect with client-side code.

How to create a cookie with a variable value

I need to create a javascript cookie in order to do something with PHP (to be exactly, I need to get the viewport height of the browser, store that in a javascript cookie in order to get the value inside PHP). The only problem is I have no javascript experience, and I dont't understand google's explanation.
I'd like to have this value (var viewportHeight = $(window).height();) inside a cookie.
But how?
(google only gives examples with a static value).
try something like this:
var viewportHeight = $(window).height();
document.cookie = "viewportheight=" + viewportHeight + ";";
You can't have dynamic values for a cookie. You can however update the cookie every time the window resizes:
$(function(){
$(window).resize(function () {
createCookie( 'viewportHeight', $(window).height() );
});
});
// You should also use some cross-browser cookie functions that make your life a lot easier
// function taken from: http://www.quirksmode.org/js/cookies.html
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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
This way you can simulate "dinamic" values for a cookie.
Alternatively, you can just send the value via ajax to a php script every time the browser resizes, without having to use cookies at all
Seems like a bad idea to me. Your layout shouldn't required the exact pixel dimensions on the server side. But, if you really have no other option:
Use this jQuery plugin: https://github.com/carhartl/jquery-cookie
Then you can do the following:
// save the window height to a cookie whenever window is resized
$(window).resize(function(){
$.cookie('viewportHeight', $(window).height(), {path:'/'});
});
// trigger the resize function so it saves the cookie on first load
$(window).load(function(){
window.setTimeout(function() {$(window).resize();}, 0);
}
Then you access it from PHP in subsequent requests like so:
$viewportHeight = $_COOKIE['viewportHeight'];
Please note that if you need the cookie value in PHP before the user sees the first page, this will not work.

Reading web-page cookies from a Firefox extension (XUL)

I'm creating an extension for the Firefox browser. I would like to read a cookie which was set by an HTML page using JavaScript in the XUL file. Is it possible?
I tried using document.cookie, but it doesn't work:
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);
}
Could you help me? Thanks in advance.
These code snippets may help
///By this method you can iterate throug each cookie by its name or value...
function ReadCookie()
{
var cookieMgr = Components.classes["#mozilla.org/cookiemanager;1"]
.getService(Components.interfaces.nsICookieManager);
for (var e = cookieMgr.enumerator; e.hasMoreElements();) {
var cookie = e.getNext().QueryInterface(Components.interfaces.nsICookie);
dump(cookie.host + ";" + cookie.name + "=" + cookie.value + "\n");
///Your code here to check your cookie or your implementation...
///You can use cookie name or value to select your cookie...
}
}
///If you want to read cookies by domain name you can use this code...
function GetCookie(){
try
{
alert("Getting Cookies");
var ios = Components.classes["#mozilla.org/network/io-service;1"]
.getService(Components.interfaces.nsIIOService);
var uri = ios.newURI("http://www.yoursite.com/", null, null);
var cookieSvc =
Components.classes["#mozilla.org/cookieService;1"]
.getService(Components.interfaces.nsICookieService);
var cookie = cookieSvc.getCookieString(uri, null);
///Your logic here...
}
catch (errorInfo)
{
alert(errorInfo);
}
}
Hope these will help :)
You probably want to use the nsICookieService interface: https://developer.mozilla.org/en/Code_snippets/Cookies
(Found via the helpful search on Mozilla's Add-on Developer Hub: https://addons.mozilla.org/en-US/developers/search?q=cookie)
You also might want to look at existing extensions that work with cookies, such as FireCookie.
There are at least two distinct ways of doing this:
Firstly, if you simply want to interact with the Firefox cookie store, you can use the nsICookieManager and nsICookieManager2 interfaces to query, add and remove cookies.
Secondly, if you're more comfortable with the document.cookie approach, and you want to deal with documents which are already loaded in the browser, you can do this, but the important thing to remember is to get the right document to work with. When you simply use document in XUL code, you are referring to the document object associated with the browser window in which you are running. Several pages might be loaded in different tabs within this window, each of which will have its own document object. As a result, you first need to find the document object that you are interested in. One way of doing this, for example, is to register to be notified of pages loads, and then to examine pages as they load to see whether they are of interest. For example, your XUL code might look like this:
function pageLoad (event) {
if (event.originalTarget instanceof HTMLDocument) {
var doc = event.originalTarget;
if (doc.URL.match(/^https?:\/\/[^\/]*\.example\.com\//)) {
⋮
doc.cookie = 'cookie_name' + "=" + value + ";expires=" +
(new Date(2050, 10, 23)).toGMTString();
⋮
}
}
}
var appcontent = document.getElementById("appcontent"); // locate browser
if (appcontent)
appcontent.addEventListener("load", function (e) { pageLoad(e); }, true);
With this approach you can interact with just those cookies associated with that page using the mechanisms with which you are familiar, and without worrying about dealing with cookies associated with completely different pages.

Categories

Resources