您可以通过编写一个非常简单的freshVistor(howFresh) 函数来解决这个问题,该函数接受一个可选参数来定义您认为“新鲜”的新鲜程度。
function freshVisitor(howFresh) {
var namespace = 'freshVisitorSOCookie';
if (readCookie(namespace)) {
return false;
}
return makeCookie(namespace, 'yes', {
expires: howFresh || 1
});
}
您的应用程序可以像这样使用freshVisitor() 函数:
if (freshVisitor()) {
/* This means the user is new or has not visited within 1 day
* So show your banner or do something that you want to do */
} else {
/* The user has visited already within the previous day
* or has disabled cookies. */
}
你也可以指定你自己对“新鲜”的定义:
if (freshVisitor(2)) ... /* uses a 2-day period to calculate freshness */
请注意!为了用户友好,我在用户禁用 cookie 时使此功能自动返回 false,以防止没有 cookie 的人被横幅广告淹没。我相信这是对待访问我网站的人的正确方式,但如果您希望扭转这种尊重行为,请随时调整我的 freshVisitor() 代码中的逻辑。
当然,您需要适当的 cookie 函数来使用上面的表示法计算到期日期,所以这里是完整的代码:
<script>
function makeCookie(name, value, p) {
var s, k;
function reldate(days) {
var d;
d = new Date();
d.setTime(d.getTime() + days * 86400000);
return d.toGMTString();
}
s = escape(name) + '=' + escape(value);
if (p)
for (k in p) {
/* convert a numeric expires value to a relative date */
if (k == 'expires')
p[k] = isNaN(p[k]) ? p[k] : reldate(p[k]);
/* The secure property is the only special case
here, and it causes two problems. Rather than
being '; protocol=secure' like all other
properties, the secure property is set by
appending '; secure', so we have to use a
ternary statement to format the string.
The second problem is that secure doesn't have
any value associated with it, so whatever value
people use doesn't matter. However, we don't
want to surprise people who set { secure: false }.
For this reason, we actually do have to check
the value of the secure property so that someone
won't end up with a secure cookie when
they didn't want one. */
if (p[k])
s += '; ' + (k != 'secure' ? k + '=' + p[k] : k);
}
document.cookie = s;
return readCookie(name) == value;
}
function readCookie(name) {
var s = document.cookie,
i;
if (s)
for (i = 0, s = s.split('; '); i < s.length; i++) {
s[i] = s[i].split('=', 2);
if (unescape(s[i][0]) == name)
return unescape(s[i][1]);
}
return null;
}
function removeCookie(name) {
return !makeCookie(name, '', {
expires: -1
});
}
function freshVisitor(howFresh) {
var namespace = 'freshVisitorSOCookie';
if (readCookie(namespace)) {
return false;
}
return makeCookie(namespace, 'yes', {
expires: howFresh || 1
});
}
document.write('Fresh visitor status: ', freshVisitor());
</script>