PDA

View Full Version : Creating a cookie after executing function



CasJ
11-16-2012, 08:29 PM
Hello there!

So basically what i want to get is a script that will create a cookie after a function is executed. But on forehand it will be checked if that cookie already exists. When this is the case i don't want the function to be executed.


<script type="text/javascript">
function csearch(DBadblockblocker) {
var str = document.cookie;
var zstr = DBadblockblocker + "=";
var start = str.indexOf(zstr, 0);
if(start == -1) {
// If cookie is not detected -> Check if Adblock is enabled
adblockcheck();
// After the popup a cookie called DBadblockblocker met value true word aangemaakt
document.cookie = "DBadblockblocker=true;path=/";
alert('Cookie is aangemaakt');
// Give alert when cookie has been made
} else {
alert('Cookie bestond al');
// Give alert when cookie already excists
}
}
</script>

I've added these 2 alerts because it was not working, but i just can't find the problem.

Hope you guys can help me!

vwphillips
11-17-2012, 10:15 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<script type="text/javascript">
function csearch(nme){
if (!cookie(nme)){
alert('set the cookie');
var days=1;
document.cookie=nme+'=true;expires='+(new Date(new Date().getTime()+days*86400000).toGMTString())+';path=/';
}
else {
alert('the cookie has been set');
}
}

function cookie(nme){
var re=new RegExp(nme+'[^;]+','i');
if (document.cookie.match(re)){
return document.cookie.match(re)[0].split("=")[1];
}
return null
}


</script>

</head>

<body>
<input type="button" name="" value="test" onmouseup="csearch('nme');"/>
</body>

</html>

clueful
11-18-2012, 03:00 AM
var start = str.indexOf(zstr, 0);
document.cookie may contain other data other than that you set, therefore the above test is flawed.

jscheuer1
11-18-2012, 07:02 PM
Also, having a global object named cookie can conflict with, well I'm not sure, it's either document.cookie or perhaps they have a global already or perhaps it's just a reserved word, etc. In any case, in some browsers it won't work.

See:

http://www.dynamicdrive.com/forums/entry.php?32-Compact-Cookie-Unit

for my take on adding/reading/managing cookies.