проверить куки, если куки существуют - PullRequest
64 голосов
/ 11 мая 2011

Какой хороший способ проверить наличие файла cookie?

Условия:

Cookie существует, если

cookie1=;cookie1=345534;
//or
cookie1=345534;cookie1=;
//or
cookie1=345534;

Cookie не существует, если

cookie=;
//or
<blank>

Ответы [ 11 ]

102 голосов
/ 11 мая 2011

Вы можете вызвать функцию getCookie с именем нужного вам куки, а затем проверить, равен ли он нулю.

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
        end = dc.length;
        }
    }
    // because unescape has been deprecated, replaced with decodeURI
    //return unescape(dc.substring(begin + prefix.length, end));
    return decodeURI(dc.substring(begin + prefix.length, end));
} 

function doSomething() {
    var myCookie = getCookie("MyCookie");

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
    }
    else {
        // do cookie exists stuff
    }
}
65 голосов
/ 02 сентября 2014

Я создал альтернативную не-jQuery-версию:

document.cookie.match(/^(.*;)?\s*MyCookie\s*=\s*[^;]+(.*)?$/)

Она проверяет только наличие файлов cookie.Более сложная версия также может возвращать значение файла cookie:

value_or_null = (document.cookie.match(/^(?:.*;)?\s*MyCookie\s*=\s*([^;]+)(?:.*)?$/)||[,null])[1]

Вместо имени MyCookie.

укажите название файла cookie
21 голосов
/ 06 ноября 2016
document.cookie.indexOf('cookie_name=');

Он вернет -1, если этот файл cookie не существует.

ps Единственным недостатком является (как упомянуто в комментариях), что он допустит ошибку, если файл cookie установлен с таким именем:any_prefix_cookie_name

( Источник )

8 голосов
/ 15 ноября 2017

ВНИМАНИЕ! выбранный ответ содержит ошибку (ответ Яка).

если у вас более одного файла cookie (очень вероятно ..), и файл cookie, который вы извлекаете, является первым в списке, он не устанавливает переменную «конец» и, следовательно, возвращает всю строку символов после "cookieName =" в строке document.cookie!

вот пересмотренная версия этой функции:

function getCookie( name ) {
    var dc,
        prefix,
        begin,
        end;

    dc = document.cookie;
    prefix = name + "=";
    begin = dc.indexOf("; " + prefix);
    end = dc.length; // default to end of the string

    // found, and not in first position
    if (begin !== -1) {
        // exclude the "; "
        begin += 2;
    } else {
        //see if cookie is in first position
        begin = dc.indexOf(prefix);
        // not found at all or found as a portion of another cookie name
        if (begin === -1 || begin !== 0 ) return null;
    } 

    // if we find a ";" somewhere after the prefix position then "end" is that position,
    // otherwise it defaults to the end of the string
    if (dc.indexOf(";", begin) !== -1) {
        end = dc.indexOf(";", begin);
    }

    return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, ''); 
}
6 голосов
/ 01 февраля 2013

Если вы используете jQuery, вы можете использовать плагин jquery.cookie .

Получение значения для определенного cookie производится следующим образом:

$.cookie('MyCookie'); // Returns the cookie value
3 голосов
/ 05 января 2017

regexObject. test (String) на быстрее , чем строка. match (RegExp).

Сайт MDN описывает формат для document.cookie и содержит пример регулярного выражения для получения файла cookie (document.cookie.replace(/(?:(?:^|.*;\s*)test2\s*\=\s*([^;]*).*$)|^.*$/, "$1");). Исходя из этого, я бы пошел на это:

/^(.*;)?\s*cookie1\s*=/.test(document.cookie);

Вопрос, кажется, требует решения, которое возвращает false, когда cookie установлен, но пусто. В этом случае:

/^(.*;)?\s*cookie1\s*=\s*[^;]/.test(document.cookie);

Тесты

function cookieExists(input) {return /^(.*;)?\s*cookie1\s*=/.test(input);}
function cookieExistsAndNotBlank(input) {return /^(.*;)?\s*cookie1\s*=\s*[^;]/.test(input);}
var testCases = ['cookie1=;cookie1=345534;', 'cookie1=345534;cookie1=;', 'cookie1=345534;', ' cookie1 = 345534; ', 'cookie1=;', 'cookie123=345534;', 'cookie=345534;', ''];
console.table(testCases.map(function(s){return {'Test String': s, 'cookieExists': cookieExists(s), 'cookieExistsAndNotBlank': cookieExistsAndNotBlank(s)}}));

Test results (Chrome 55.0.2883.87)

1 голос
/ 19 сентября 2018

Это старый вопрос, но вот подход, который я использую ...

function getCookie(name) {
    var match = document.cookie.match(RegExp('(?:^|;\\s*)' + name + '=([^;]*)')); return match ? match[1] : null;
}

Возвращает null либо когда cookie не существует, либо когда он не содержит запрошенного имени.
В противном случае возвращается значение (запрошенного имени).

Печенье никогда не должно существовать без значения - потому что, честно говоря, какой в ​​этом смысл? ?
Если он больше не нужен, лучше всего избавиться от всего этого вместе.

function deleteCookie(name) {
    document.cookie = name +"=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
}
1 голос
/ 11 сентября 2017
function getCookie(name) {

    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
        else{
            var oneCookie = dc.indexOf(';', begin);
            if(oneCookie == -1){
                var end = dc.length;
            }else{
                var end = oneCookie;
            }
            return dc.substring(begin, end).replace(prefix,'');
        } 

    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
        var fixed = dc.substring(begin, end).replace(prefix,'');
    }
    // return decodeURI(dc.substring(begin + prefix.length, end));
    return fixed;
} 

Попробовал функцию @jac, возникли проблемы, вот как я отредактировал его функцию.

0 голосов
/ 04 июля 2018

используйте этот метод вместо:

function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
    else return null;
}

function doSomething() {
    var myCookie = getCookie("MyCookie");

    if (myCookie == null) {
        // do cookie doesn't exist stuff;
    }
    else {
        // do cookie exists stuff
    }
}
0 голосов
/ 09 марта 2018

Для тех, кто использует Node, я нашел хорошее и простое решение с импортом ES6 и модулем cookie!

Сначала установите модуль cookie (и сохраните его как зависимость):

npm install --save cookie

Затем импортируйте и используйте:

import cookie from 'cookie';
let parsed = cookie.parse(document.cookie);
if('cookie1' in parsed) 
    console.log(parsed.cookie1);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...