I have a JavaScript function that stores the cookie value, and I want to insert it into a field in an HTML form (as in Facebook – having your e-mail prefilled after logging out).
The cookie originally is shown up with document.write.
I imagine I have to:
get the value of the VisitorName cookie
convert document.write to text
insert this text by changing input value through
document.getElementById('inputID').value = cookie value"
How can I do this? Here is the code:
var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));
function Who(info) {
var VisitorName = GetCookie('VisitorName')
if (VisitorName == null) {
VisitorName = "Dear visitor";
SetCookie ('VisitorName', VisitorName, exp);
}
return VisitorName;
}
function set() {
VisitorName = prompt("");
SetCookie ('VisitorName', VisitorName, exp);
}
function getCookieVal (offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0)
break;
}
return null;
}
function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc>2) ? argv[2] : null;
var path = (argc >3) ? argv[3] : null;
var domain = (argc >4) ? argv[4] : null;
var secure = (argc >5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : (";expires=" + expires.toGMTString())) +
((path == null) ? "" : (";path=" + path)) +
((domain == null) ? "" : (";domain=" + domain)) +
((secure == true) ? ";secure" : "");
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
document.write("" + Who() + ",")
Your post has already answered your own question. Putting the listings together:
<input id="visitor">
<script>
document.getElementById('visitor').value = GetCookie('VisitorName');
</script>
document.getElementById('inputID').value = GetCookie('VisitorName');
Related
I'm trying to store cookies for four different parameters in a URL. I have it working where it'll detect if the cookie is present, if it isn't, it'll add it. I also have it set detect if they come in from another URL string with those parameters but they're different–it'll overwrite the old cookie with the new cookie information, and if the parameter is blank, it'll return null.
The thing I'm having trouble implementing is that I ONLY want it replacing the cookies if the URL string contains a different set of parameters where one at least one of them isn't null. If all four parameters are null, but there are cookies stored, I don't want it replacing the cookie.
Here's the script I have:
function queryParam(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var source = queryParam('utm_source');
var campaign = queryParam('utm_campaign');
var medium = queryParam('utm_medium');
var content = queryParam('utm_content');
function setCookie(utm, utmvar, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = utm + "=" + utmvar + ";" + expires + ";path=/";
}
function getCookie(utm) {
var name = utm + "=";
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 "";
}
function checkCookie() {
var utmSource = getCookie("utm_source");
if (utmSource != "") {
if (utmSource = source) {
utmSource = utmSource;
}
else {
setCookie("utm_source", utmSource, 7);
}
}
else {
utmSource = source;
if (utmSource != "" && utmSource != null) {
setCookie("utm_source", utmSource, 7);
}
}
var utmCampaign = getCookie("utm_campaign");
if (utmCampaign != "" ) {
if (utmCampaign = campaign) {
utmCampaign = utmCampaign;
}
else {
setCookie("utm_campaign", utmCampaign, 7);
}
}
else {
utmCampaign = campaign;
if (utmCampaign != "" && utmCampaign != null) {
setCookie("utm_campaign", utmCampaign, 7);
}
}
var utmMedium = getCookie("utm_medium");
if (utmMedium != "" ) {
if (utmMedium = medium) {
utmMedium = utmMedium;
}
else {
setCookie("utm_medium", utmMedium, 7);
}
}
else {
utmMedium = medium;
if (utmMedium != "" && utmMedium != null) {
setCookie("utm_medium", utmMedium, 7);
}
}
var utmContent = getCookie("utm_content");
if (utmContent != "") {
if (utmContent = content) {
utmContent = utmContent;
}
else {
setCookie("utm_content", utmContent, 7);
}
}
else {
utmContent = content;
if (utmContent != "" && utmContent != null) {
setCookie("utm_content", utmContent, 7);
}
}
var sbaValue = utmCampaign + ";" + utmSource + ";" + utmMedium + ";" + utmContent;
$("#00N0B000005VTnf").attr("value", sbaValue);
}
So an example of how I want to act would be - if the URL string is:
domain.com/?utm_source=b&utm_medium=a&utm_campaign=c&utm_content=d => sbaValue = a;b;c;d
Then they come in at:
domain.com/?utm_medium=a&utm_campaign=c&utm_content=d => sbaValue = a;null;c;d
Then they come in at:
domain.com/ => sbaValue = a;null;c;d (nothing changes from before)
I tried setting a variable when something isn't null, but no matter how I implemented it, I couldn't get it to work.
if(["utm_campaign","utm_whatever"].some(el=>queryParam(el)){
... change
}
Simply check if there are params before doing the cookiestuff...
By the way, you can safe much time using the OR operator:
setCookie("utm_source",queryParam("utm_source")||getCookie("utm_source")||alternative, 7);
I ended up rewriting a lot of it and cleaned it up A LOT. Here's the final solution:
function queryParam(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function setCookie(utm, utmvar, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires="+d.toUTCString();
document.cookie = utm + "=" + utmvar + ";" + expires + ";path=/";
}
function getCookie(utm) {
var name = utm + "=";
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 "";
}
function getQueryStringVariables(){
return {
source: queryParam('utm_source'),
campaign: queryParam('utm_campaign'),
medium: queryParam('utm_medium'),
content: queryParam('utm_content'),
}
}
function isQueryStringSet(){
var queryStringVariables = getQueryStringVariables();
if (queryStringVariables.source ||
queryStringVariables.campaign ||
queryStringVariables.medium ||
queryStringVariables.content) {
return true;
}
return false;
}
function fetchCookieData() {
return {
source: getCookie("utm_source"),
campaign: getCookie("utm_campaign"),
medium: getCookie("utm_medium"),
content: getCookie("utm_content"),
};
};
function updateCookie() {
var queryStringVariables = getQueryStringVariables();
if (isQueryStringSet()) {
setCookie("utm_source", queryStringVariables.source, 7);
setCookie("utm_campaign", queryStringVariables.campaign, 7);
setCookie("utm_medium", queryStringVariables.medium, 7);
setCookie("utm_content", queryStringVariables.content, 7);
}
}
function updateFormValue() {
var cookieData = fetchCookieData();
var sbaValue = cookieData.campaign + ";" + cookieData.source + ";" + cookieData.medium + ";" + cookieData.content;
$("#00N0B000005VTnf").attr("value", sbaValue);
}
updateCookie();
updateFormValue();
So I am new to JavaScript and I'm kinda stuck.
I want to allow my cookie to work on all of my pages.
I know that I need to add "/" to path. The only problem is that the little script I got is a bit different than all the examples out there.
Does somebody know where to put it?
var expdate = new Date();
expdate.setTime(expdate.getTime() + (24 * 60 * 60 * 1000 * 365));
function setCookie(name, value, expires, path, domain, secure) {
var thisCookie = name + "=" + escape(value) + ((expires) ? "; expires=" +
expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? ";domain=" + domain : "") + ((secure) ? "; secure" : "");
document.cookie = thisCookie;
}
function showCookie() {
alert(unescape(document.cookie));
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) return getCookieVal(j);
i = document.cookie.indexOf(" ", i) + 1;
if (i === 0) break;
}
return null;
}
function MyNamer() {
var now = new Date();
now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
var username = GetCookie("username");
if ((!username) || (username == 'null')) {
username = prompt("What is your name?:", "");
}
setCookie("username", username, now);
if (username) {
document.write(username);
setCookie("username", username, now);
} else
document.write("Guest")
}
Thanks in advance!
Well, from your code it looks like the 4th argument in setCookie is the one you want:
setCookie(name, value, expires, path, domain, secure)
e.g.setCookie("myCookie", "myCookieValue", new Date(), "/")
What are you using the cookie for? The webserver you're making the request from controls cookie data, including path. If you're just storing data then you could use the browsers' local/session storage objects?
Hi I need to know is how to read cookies on a html web-view . I have a banner to close it generates a cookie and the idea would be to go to another page that has the banner he would read the cookie to see if the User already have clicked ...
this is the cookie code
function createCookie() {
var d = new Date();
d.setTime(d.getTime() + (1*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = "cookie=cookie ; " + expires+';path = http://www.pitstop.com.br/';
document.getElementById('banner_id').style.display='none';
}
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 null;
}
function banner_cookie(){
var teste = getCookie('cookie');
if(teste !=null){
alert(teste);
document.getElementById('banner_id').style.display='none';
}else{
document.getElementById('banner_id').style.display
}
}
You have many issues that seems to stem from wishful thinking and misunderstanding.
For example your path is wrong and you need to pass a name to the cookie script instead of hardcoding the name "cookie"
You need to take a well tested cookie script and use it properly.
function getCookie(name) {
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if ((!start) && (name != document.cookie.substring(0, name.length))) {
return null;
}
if (start == -1) return null;
var end = document.cookie.indexOf(';', len);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function setCookie(name, value, expires, path, domain, secure) {
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + '=' + escape(value) +
((expires) ? ';expires=' + expires_date.toGMTString() : '') + //expires.toGMTString()
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
((secure) ? ';secure' : '');
}
function deleteCookie(name, path, domain) {
if (getCookie(name)) document.cookie = name + '=' +
((path) ? ';path=' + path : '') +
((domain) ? ';domain=' + domain : '') +
';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}
Your script:
function banner_cookie(){
var teste = getCookie('showbanner')=="true";
document.getElementById('banner_id').style.display=teste?"block":"none";
}
and to set:
setCookie("showbanner","true",14,"/"); // 2 weeks accessible to all website
and to remove
deleteCookie("showbanner","/");
I'm trying to make a popup that appears on my site the first time you visit it. But not any other time after that. So I'm trying to make it with cookies. But I'm having absolutely no luck.
I've tried following W3 school's tutorial but I haven't gotten anywhere.
What I'm doing is when the user closes the dialog, it sets a cookie. And I'm trying to make it so when you come back, the pop up doesn't appear because the cookie is set.
Here's my code.
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;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0)
return c.substring(name.length,c.length);
}
return "";
}
function checkCookie() {
var username=getCookie("username");
if (username!="") {
$('#firsttimee').css({display : 'none'});
} else {
if (username=="" || username==null) {
$('#firsttimee').css({display : 'block'});
}
}
}
function closepop(){
$('#firsttimee').css({display : 'none'});
var username = 'seen';
setCookie("username",username,365);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firsttimee">
<div id="firsttimetxt">
<center>
Click here.<br><br>
Done
</center>
</div>
</div>
Thanks in advance! :)
Here is a jsfidddle of my current work, for some reason when you click done the popup doesn't go away..
Use the cookie script from MDN, not W3Schools, looks like W3Schools is not setting the path.
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
var sExpires = "";
if (vEnd) {
switch (vEnd.constructor) {
case Number:
sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
break;
case String:
sExpires = "; expires=" + vEnd;
break;
case Date:
sExpires = "; expires=" + vEnd.toUTCString();
break;
}
}
document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
return true;
},
removeItem: function (sKey, sPath, sDomain) {
if (!sKey || !this.hasItem(sKey)) { return false; }
document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
},
keys: /* optional method: you can safely remove it! */ function () {
var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
return aKeys;
}
};
and to set the cookie
docCookies.setItem("username",username,"Infinity");
and to get the cookie
docCookies.getItem("username") //returns the string
or
docCookies.has("username") //return boolean
I usually use below code for that:
function getCookie(cookieName) {
var i, x, y, cookiesArray = document.cookie.split(";");
for (i = 0; i < cookiesArray.length; i++) {
x = cookiesArray[i].substr(0, cookiesArray[i].indexOf("="));
y = cookiesArray[i].substr(cookiesArray[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == cookieName) {
return unescape(y);
}
}
}
function checkCookie() {
hideCookieDiv();
var myCookie = getCookie("yourcookiename");
if (myCookie == null || myCookie != "true") {
showCookieDiv();
setCookie();
}
}
function hideCookieDiv() {
document.getElementById('YourDivId').style.display = "none";
}
function showCookieDiv() {
document.getElementById('YourDivId').style.display = "block";
}
function setCookie() {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + 365);
document.cookie = "yourcookiename=true; expires=" + expirationDate.toUTCString();
}
I am trying to find out if its the users first time on my webpage. I am currently storing a variable in local storage and checking if its null or not but it doesn't seem to work in Internet Explorer. What other method can I use to accomplish this?
var str_count = localStorage.getItem("count");
if (str_count == null || str_count == "null")
{
// Do something
}
Setting cookie with long expiration date is definitely more reliable that using localStorage as it is not yet supported by older browsers.
Check this code:
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);
}
Read more about cookies here.
You can set a cookie with
document.cookie = name + "=" + value + "; expires=" + exp + "; path=/";
More info here: http://www.w3schools.com/js/js_cookies.asp
More info here: http://www.quirksmode.org/js/cookies.html
As #Greg said, the better solution is to set and get cookie values. Here's two functions to do this:
setCookie = function(){
var args = arguments,
name = (args[0] ? args[0] : '') + '=',
_value = args[1] ? escape(args[1]) : '',
value = _value + ';',
expires = args[2] ? 'expires=' + args[2].toUTCString() + ';' : '',
path = args[3] ? 'path=' + args[3] + ';' : '',
domain = args[4] ? 'domain=' + args[4] + ';' : '',
secure = args[5] ? 'secure;' : '',
newCookie = name + value + expires + path + domain + secure;
document.cookie = newCookie.match(/[a-z||A-Z]/) ? newCookie : ''
return _value;
},
getCookie = function(name){
if(!name || name.replace(/[^a-z|0-9|çáéíóúãõâêîôûàèìòùäëïöü]/,'')=='*') return document.cookie;
var ck = ' ' + document.cookie + ' ',
pos = ck.search(' ' + name + '='),
pos = (pos!=-1) ? pos + 1 : ck.length,
ck = ck.substring(pos-1,ck.length),
end = (ck.search('; ')!=-1) ? ck.search('; ') : ck.length,
value = ck.substring(((ck.search('=')!=-1) ? (ck.search('=')+1) : end),end);
return unescape((value[value.length-1]==' ') ? value.substring(0,value.length-1) : value);
}
They're crossbrowser functions. To use getCookie function, just use the name parameter, and with the setCookie function, use the name,value,expires,path,domain,secure parameters