/    Sign up×
Community /Pin to ProfileBookmark

Is using an html page’s onload event too early to check cookies?

I’m currently using cookies on my site to to count how many times a visitor has been there, and to try to have a reasonably useful “unique visitor” count. I’m having an intermittent problem. The way its supposed to work is if the visitor cookie is **not** found, I’ll usually display a message with some necessary site info. Or, if the cookie **is found** I’ll display a small “welcome back” banner. The problem I’m having is that despite giving the cookie an expiration time of over a year, I’ll **sometimes** test the page only to find my “new visitor” message pops up. Note the operative word is “**sometimes**“!

I have a hidden “diagnostic” window on may pages which I can bring up to see what’s going on, and it always shows that the visitor cookie is indeed present,,and has an expected count, even when the new visitor message was triggered. So I’m wondering now whether I should be delaying my cookie test until several seconds AFTER the body’s onload event?

to post a comment
JavaScript

6 Comments(s)

Copy linkTweet thisAlerts:
@daveyerwinMay 01.2019 — Note the operative word is "sometimes" will make this hard to diagnose.

Post the faulty code here or a link to the page.
Copy linkTweet thisAlerts:
@PeterPan_321authorMay 01.2019 — Uggg...@DaveyErwin#1603211 its hard to "really' post the code, without posting ALL of it. But to start, I have a call in the <body "onload="doOnloadStuf(); and one of the last things I do in that "doOnloadStuff() call is this little snipit, which just changes the text in a "new visitors click here" DIV (with an ID="'introTxt") to a ""welcome back message...

[code=javascript]

<script>
if (readCookie(getCookieName(0)) == null) {
var ic=0;
var si = setInterval(function() {
toggleVis('introTxt', (++ic & 1)); // blink
if (ic > 50) { clearInterval(si); } // even== left on
}, 1000);
}
else document.getElementById('introTxt').innerHTML=
"<em>* Welcome Back! *</em>";

newVisitorMessage(0);

</script>
[/code]


so toggleVis() is just a convenience function to make a DIV show up on the page

[code=javascript]
function toggleVis(id, state) {
try {
var aud = document.getElementById(id);
aud.style.visibility= (state) ? 'visible' :'hidden';
return aud;
}
catch(ignore) { return null} // continue regardless
}
[/code]


also "readCookie()" is defined as...

[code=javascript]
// read a cookie, if found return its value, else null

function readCookie(cookieName)
{
var nameEQ = cookieName + "=";

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;
}

[/code]


and getCookieName(0) is just...

[code=javascript]

function getCookieName(n) {
var cnames = ["pastVisitor"];
if (n >= cnames.length) return null;
return cnames[n];
}
[/code]


There is also that newVisitorMessage() call that triggers whether or not to display a "new visitor" message, This one actually updates the cookie. For this, please trust that "myreport" is a call that stores diagnostic text for later debug display, sRefWindowNew() is a call that displays (in this case) the new visitor message.


[code=javascript]

function newVisitorMessage(bypass) {
var cookieName = getCookieName(0);
var expireDays = 365; // a year. or one day to test
var cval;

if (bypass == false) {
cval = readCookie(cookieName);
if (cval != null) {
myreport(cookieName + " cookie found. val= " + cval);
eraseCookie(cookieName);
cval = parseInt(cval); // in case it was a string
createCookie(cookieName, ++cval, setCookieTime(expireDays));
return true;
}
myreport(cookieName + " cookie not found");
createCookie(cookieName,"1", setCookieTime(expireDays));
var cval = readCookie(cookieName); // verify???
myreport("cookieName" + "= " + cval + " after set attempt");
}

sRefWindowNew("/scriptref/newvisitor.html", null);

}

// other dependent calls used in above...

// read a cookie, if found return its value, else null

function readCookie(cookieName)
{
var nameEQ = cookieName + "=";

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;
}


//erase cookie
function eraseCookie(cookieName)
{
if (readCookie(cookieName) != null)
createCookie(cookieName,"",-1);

}


// create a cookie
function createCookie(cookieName,value, timeInSeconds) {
var expires ="";
if (timeInSeconds)
{
var date = new Date();
date.setTime(date.getTime()+timeInSeconds*1000);
expires = "; expires="+date.toGMTString();
}
document.cookie = cookieName+"="+value+expires+"; path=/";
}



[/code]


If it matters, the website is here...

http://throughthecracks.org/

When it fails, both the "welcome back" text change AND the suppression of the new visitor message fails. But again, it only happens sometimes... usually after a day, when the browser has been closed and re-opened. Doesn't make sense because I've checked the cookies in my browser, and their expiration dates are indeed a year in the future. I should hasten to point out that I don't want to burden anyone with analyzing all my calls. I mainly want to know if in principal, I should be waiting a little while after onLoad() completes before checking cookies.
Copy linkTweet thisAlerts:
@daveyerwinMay 01.2019 — Thank you for supplying the link

I found the content enjoyable

I was unable to reproduce the anomaly

I did confirm that the cookie expires after one year

Is there a chance that the cookie is being deleted by your browser ?

Are you using more than one browser to view the page ?

the cookie will not be available to other browsers on your machine until it is created by

that browser

and

while this is unrelated I will point out that ...

function getCookieName(n) {

var cnames = ["pastVisitor"];

if (n >= cnames.length) return null;

return cnames[n];

}

is equivalent to ...

function getCookieName(n) {

return n?null:"pastVisitor";

}
Copy linkTweet thisAlerts:
@PeterPan_321authorMay 01.2019 — @DaveyErwin#1603229

Well thanks... it is ALWAYS good to know other's are not seeing the problem I see, and I do appreciate you're sanity checking my code.. Yes that getCookieName() is kind of temporary and incomplete... I had intended to populate the array with other cookie names, but may not need to. Yes... when one fails, the other fails. But as i mentioned, I have a "hidden" diagnostic on the page (scroll all the way to the bottom, and find the little ""B" all the way at the lower right, and click it 3 times. My diagnostic window pops up, and one of the first things it does is display ALL cookies, including a session cookie I use for a unique visitor count, along with the "pastVisitor" cookie. Since anytime I find that cookie I destroy it and then recreate it after incrementing its count, its doubly puzzling when the initial cookie action fails, and then I activate my diag, and it shows the "pastVisitor" cookie with a positive value >= 2, meaning there is no reason initial visitor message action should have failed. All i could think of was the fact that the diag, being launched manually, is definitely checking cookies well after page load. So I guess I'll try to move all the initial cookie actions to happen after my setInterval call fires. I know that's the same as a blind many throwing darts, but its the only thing i can think of to try.

The mysteries of browsers!
Copy linkTweet thisAlerts:
@KxmodeMay 02.2019 — If you're not too terribly opposed to jQuery, I highly recommend using that to give you more control over when and where to check things. For example, the following will wait until the entire page is fully rendered before it will execute the script.

<i>
</i>$(window).on("load", function() {
// do something
});


Note: the above is for the latest jQuery syntax I believe post 2.X. For other versions the code looks like:

<i>
</i>$(window).load(function() {
// do something
});


If you grab the jQuery Cookies addon at https://github.com/js-cookie/js-cookie then you can quickly check for cookies like this.

<i>
</i>if ($.cookie("cookiename")) {
// do something
}


So putting it all together using the latest syntax:

<i>
</i>$(window).on("load", function() { // Wait until the page is fully loaded...
if ($.cookie("cookiename")) { // If a cookie called cookiename exists and it has a value...
// do something
}
});


Given that jQuery and jQuery Cookie are browser agnostic it tends to be a good alternative to pure JavaScript. That's my humble opinion of course. 😅
Copy linkTweet thisAlerts:
@PeterPan_321authorMay 02.2019 — @Kxmode#1603266 Well, I appreciate the suggestion. I have not officially used Jquery, and I appreciate your final comment. I guess its the "old school" in me. Not that I'm any kind of expert, but I've been at this since 2001, and so far have found very few situations where I couldn't do in pure Javascript what was being suggested in JQuery. The other thing is that it seems big libraries tend to simplify what *I* have to do, by *HIDING* what is really happening. Is "$(window).on("load", function() {..." any different from directly saying "window.onload = function() {..." in Javascrip? Probably not.

But what might be more relevent to me is that I have been doing my "cookie" maintenance directly by referencing a function in my <body onload="myfunction()". Would it be better to assign my cookie functions to window.onload = function() { ??? If so, should I do that within the function I'm tying to < body onload= ?. I don't know. What are the diffecces between <body onload , window.onload, and document.onload?
×

Success!

Help @PeterPan_321 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...