【发布时间】:2013-06-15 13:51:36
【问题描述】:
试图编写一个 JavaScript 代码来检测用户是否在他们的浏览器中禁用了 cookie。如果他们这样做,他们将被重定向到另一个页面。如果他们启用了 cookie,它就会像往常一样直接通过。
我的代码已经可以使用,但在重定向之前它仍然会在页面上停留片刻。无论如何让它即时。快速检测的一个例子是here(尝试禁用cookies)http://optusnet.com.au 您会看到它是即时的,并且不会先加载页面请求。
<script type="text/javascript">
/* function to create cookie @param name of the cookie @param value of the cookie @param validity of the cookie */
function createCookie(name, value, days)
{
var expires;
if (days)
{
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = ";
expires=" + date.toGMTString();
}
else
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);
}
/* This function will create a new cookie and reading the same cookie. */
function areCookiesEnabled()
{
var r = false;
createCookie("testing", "Hello", 1);
//creating new cookie
if (readCookie("testing") != null)
{
//reading previously created
cookie r = true;
eraseCookie("testing");
}
return r; //true if cookie enabled.
}
</script>
<script>
if(!areCookiesEnabled())
{
//redirect to page
}
</script>
【问题讨论】:
-
使用 Moderizr 更新的 cookie 检测来减少代码的大小可能会有所帮助:github.com/Modernizr/Modernizr/blob/master/feature-detects/…
标签: javascript redirect cookies