如何检测是否在Javascript中设置了cookie?

时间:2014-01-18 19:44:00

标签: javascript php cookies session-cookies

我在PHP中设置了一个会话,它正在创建一个cookie:PHPSESSID ... 我可以在Chrome& Opera使用document.cookie。但是在Forefox中,document.cookie还会返回其他域名在页面上设置的Cookie,例如Google Analytics。

在PHP中我设置的会话如下:

session_start();
$_SESSION['source'] = &$ref['source'];
$_SESSION['term'] = &$ref['term'];
session_write_close();

我需要能够通过查找cookie来检测此会话是否在Javascript中设置。最好的方法是什么?

目前我正在使用:

document.cookie.indexOf( 'PHPSESSID' )

这看起来有点像拙劣。

2 个答案:

答案 0 :(得分:1)

使用这个Jquery插件,它太酷了。

https://github.com/carhartl/jquery-cookie

您可以这样使用它:

if($.cookie('PHPSESSID') != undefined){
 //PHPSESSID exists
}

答案 1 :(得分:1)

document.cookie属性将返回所有cookie。虽然indexOf会起作用,但如果您的cookie实际数据包含“PHPSESSID”,它将会中断。它还将匹配以下cookie'MYPHPSESSIDIDIT',因为它包含您的cookie名称。

您可以使用以下函数解析cookie(未测试):

function getCookieValue(name)
{
    // find cookie entry in middle?
    var s=document.cookie,
        c=s.indexOf("; "+name+"=");

    if(c==-1)
    {
        // no, is it at the start?
        c=s.indexOf(name+"=");
        if(c!=0) return null;
    }

    // get length of value
    var l=c+name.length+1,
        e=s.indexOf(";",l);

    // is it at the end?
    if(e==-1) e-s.length;

    // cut out the value
    return s.substring(l,e);
}

希望这有帮助

相关问题