Файлы cookie ie7 не блокируются на моем сайте - PullRequest
0 голосов
/ 30 июня 2011

Я добавляю функцию на веб-сайт для моего клиента, показывая div на странице входа, если куки отключены. Сначала я начал тестировать это в Chrome, отключил куки и после

if (document.cookies == "") {
    // show div to tell users cookies are disabled on their machine.
}

все работает. Также в моем коде на Page_Load я пытаюсь установить cookie

protected void Page_Load(object sender, EventArgs e) 
{
    Response.Cookies["test"].Value = "test";
    Response.Cookies["test"].Expires = DateTime.Now.AddDays(1);
}

Все выглядит хорошо в хромированной земле. Затем я перехожу к IE7, блокирую все куки и в целях безопасности удаляю всю мою историю и куки на всякий случай. Я ожидал увидеть свой div, но не увидел.

Итак, я добавил еще один к своему if (document.cookies == "") {} прочитав cookie в javascript и убедившись, что мой тестовый cookie есть.

Я вошел в Инструменты -> Параметры Интернета -> вкладка Конфиденциальность -> и переместил ползунок до самого верха, «Блокировать все куки». На вкладке «Конфиденциальность» я нажал кнопку «Дополнительно» и установил для себя как собственные, так и сторонние файлы cookie. Я думаю, что это должно быть заблокировано.

Например, в качестве теста я захожу на google.com в ie7, он предупреждает меня, если я хочу разрешить или заблокировать два файла cookie от Google.

Что мне нужно сделать, чтобы проверить, не отключены ли cookie в ie7?

Я создал файл cookies.js для создания, чтения и удаления

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

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

function readCookie(name) {

    //  we're going to search for the name of the cookie, followed by an =. So create this new string and put it in nameEQ
    var nameEQ = name + "=";

    //  split document.cookie on the semicolons. ca becomes an array containing all cookies that are set for this domain and path.
    var ca = document.cookie.split(';');

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

        //  set c to the cookie to be checked.
        var c = ca[i];

        //  if the first character is a space, remove it by using the 'substring()' method. continue doing this until the first character is not a space.
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);

        //  now string c begins with the name of the current cookie. if this is the name of the desired cookie, we've found what we are looking for.
        //  we now only need to return the value of the cookie, which is the part of c that comes after nameEQ. By 
        //  returning this value we also end the function: mission accomplished.
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);

    }

    //  if after having gone through all cookies, we haven't found the name we are looking for, the cookie is not present, just return null.
    return null;

}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function cookiesEnabled() {
    if (document.cookies == "") {
       return false;
    }

    return true;
}

Просто скачал jquery.cookie.js и в моей функции для проверки наличия файлов cookie, у меня есть это:

function cookiesEnabled() {
    var TEST_COOKIE = 'test_cookie';
    $.cookie(TEST_COOKIE, true);
    if ($.cookie(TEST_COOKIE)) {
        $.cookie(TEST_COOKIE, null);
        return true;
    }
    return false;
}

это работает в chrome и firefox, но не в ie7.

я тоже пробовал это:

function cookiesEnabled() {
    var cookieEnabled = (navigator.cookieEnabled) ? true : false;

    if (typeof navigator.cookieEnabled === "undefined" && !cookieEnabled) {
        document.cookie = "testcookie";
        cookieEnabled = (document.cookie.indexOf("testcookie") != -1) ? true : false;
    }

    return cookieEnabled;
}

это сработало. Я думаю, что в какой-то момент или navator.cookieEnabled был поддержан ie, но похоже, что chrome и firefox также поддерживают его.

Эта штука действительно начинает действовать мне на нервы !!!

1 Ответ

0 голосов
/ 30 июня 2011

Вот старый тест, который я нашел.

Работает ли он для IE?

Для других браузеров ему нужны функции setCookie, getCookie и delCookie, которые у меня также есть, если необходимо

function isCookieEnabled() {
   if (document.all) return navigator.cookieEnabled;
   setCookie('testcookie',today.getTime());
   var tc = getCookie('testcookie');
   delCookie('testcookie');
   return (tc == today.getTime());
}

/* Cookie functions originally by Bill Dortsch */
function setCookie (name,value,expires,path,theDomain,secure) { 
   value = escape(value);
   var theCookie = name + "=" + value + 
   ((expires)    ? "; expires=" + expires.toGMTString() : "") + 
   ((path)       ? "; path="    + path   : "") + 
   ((theDomain)  ? "; domain="  + theDomain : "") + 
   ((secure)     ? "; secure"            : ""); 
   document.cookie = theCookie;
} 

function getCookie(Name) { 
   var search = Name + "=" 
   if (document.cookie.length > 0) { // if there are any cookies 
      offset = document.cookie.indexOf(search) 
      if (offset != -1) { // if cookie exists 
         offset += search.length 
         // set index of beginning of value 
         end = document.cookie.indexOf(";", offset) 
         // set index of end of cookie value 
         if (end == -1) end = document.cookie.length 
         return unescape(document.cookie.substring(offset, end)) 
      } 
   } 
} 
function delCookie(name,path,domain) {
   if (getCookie(name)) document.cookie = name + "=" +
      ((path)   ? ";path="   + path   : "") +
      ((domain) ? ";domain=" + domain : "") +
      ";expires=Thu, 01-Jan-70 00:00:01 GMT";
//   alert(name+' marked for deletion');
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...