我需要JavaScript代码来检测用户是否在浏览器中禁用了Cookie。如果他们这样做,他们将被重定向到另一页。如果他们启用了Cookie,就会像往常一样直接通过。
答案 0 :(得分:1)
您可以在浏览器中插入测试Cookie并再次回拨该Cookie。
使用此库。它具有简单的功能,可识别启用的cookie,创建/读取或删除cookie。
<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>