Jump to content
Fórum Script Brasil
  • 0

Cookies


zep

Question

Olá.

Estou começando a trabalhar com cookies.

Tenho esse código html:

<code>

<html>

<head>

<title>iRock - The Virtual Pet Rock</title>

<script type="text/javascript" src="cookie.js"></script>

<script type="text/javascript">

userName = undefined;

function resizeImg(){

var window_height = window.innerHeight||document.body.clientHeight||document.documentElement.clientHeight;

document.getElementById("rockImg").style.height = (window_height-100)*.9;

}

var idSad

function touchRock() {

if(idSad){

clearTimeout(idSad)

}

if(userName){

alert("I like the attention, "+userName+".Thank you.");

}else{

userName = prompt("What is your name?", "Enter your name here.");

if(userName){

alert("It is goot to meet you, "+userName+".");

if(navigator.cookieEnabled){

writeCookie("irock_username", userName, 5*365);

}else{

alert("Sorry. Cookies aren´t supported/enabled in your browser. I won´t remember you later.");

}

}

}

document.getElementById("rockImg").src = "rock_happy.png";

idSad = setTimeout("document.getElementById('rockImg').src = 'rock.png';", 3000)

}

function greetUser(){

if(navigator.cookieEnabled){

alert("cookie enabled");

userName = readCookie("irock_username");

alert(userName);

}

if(userName){

alert("Hello "+userName+", I missed you.");

}else{

alert("Hello, I am your pet rock.");

}

}

</script>

</head>

<body onload="resizeImg();greetUser();" onresize="resizeImg();">

<div style="margin-top:100px; text-align:center">

<img id="rockImg" src="rock.png" alt="iRock" style="cursor:pointer" onclick="touchRock();" />

</div>

</body>

</html>

</code>

E o cookie.js que é o script que gera o cookie, e outras funções mais:

<code>

function writeCookie(name, value, days){

//By default, there is no expiration so the cookie is temporary

var expires = "";

//Specifying a number of days makes the cookie persistent

if(days){

var date = new Date();

date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));

expires = "; expires=" + date.toGMTString();

}

//Set the cookie to the name, value, and expiration date

document.cookie = name + "=" + value + expires + "; path=/";

}

function readCookie(name){

//Find the specified cookie and return its value

var searchName = name + "=";

var cookies = document.cookie.split(";");

for(var i=0; i<cookies.length; i++){

var c = cookies;

while(c.charAt(0) == ' ')

c = c.substring(1, c.length);

if (c.indexOf(searchName)==0)

return c.substring(searchName.length, c.length);

}

return null;

}

function eraseCookie(name){

//Erase the specified cookie

writeCookie(name, "", -1);

}

</code>

O navigator.cookieEnabled retorna true, mas a variável "userName" é null quando dou um refresh na página.

Ou seja, o cookie não está sendo gravado, ou tem algum erro no script cookie.js que não consegue achar o cookie.

O que pode ser?

Estou rodando o código no Chrome.

No Firefox e no IE funciona.

Obrigado.

Edited by zep
Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

Cara, eu tenho uma função muito boa pra mexer com cookies, primeiro você adiciona esse script na sua página

function my_getcookie(name){cname=name+'=';cpos=document.cookie.indexOf(cname);if(cpos!=-1){cstart=cpos+cname.length;cend=document.cookie.indexOf(";",cstart);if(cend==-1){cend=document.cookie.length}return unescape(document.cookie.substring(cstart,cend))}return null}function my_setcookie(name,value,sticky,path){expires="";domain="";if(sticky){expires="; expires=Wed, 1 Jan 2020 00:00:00 GMT"}if(!path){path="/"}document.cookie=name+"="+value+"; path="+path+expires+domain+';'}
Agora, se você quiser criar um cookie em qualquer script seu você põe:
my_setcookie('NOME_DO_COOKIE','VALOR_DO_COOKIE',1,0);
Se você quiser retornar o valor de um cookie já existente você põe:
my_getcookie('NOME_DO_COOKIE');

Se o cookie não existir ele retornará o valor como null.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      152.2k
    • Total Posts
      652k
×
×
  • Create New...