简体   繁体   English

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

[英]How to detect if cookie is set in Javascript ?

I have set a session in PHP, which is creating a cookie: PHPSESSID... I can detect this in Chrome & Opera by using document.cookie. 我在PHP中设置了一个会话,它正在创建一个cookie:PHPSESSID ...我可以使用document.cookie在Chrome和Opera中检测到这一点。 However in Forefox, document.cookie also returns cookies set on the page by other domains, eg Google Analytics. 但是在Forefox中,document.cookie还会返回其他域名(例如Google Analytics)在页面上设置的Cookie。

In PHP I am setting the sessions like: 在PHP中我设置的会话如下:

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

I need to be able to detect if this session is set in Javascript, by locating the cookie. 我需要能够通过查找cookie来检测此会话是否在Javascript中设置。 What is the best way to go about this? 最好的方法是什么?

At the moment I am just using: 目前我正在使用:

document.cookie.indexOf( 'PHPSESSID' )

which seems like a bit of a botch. 这似乎有点拙劣。

Use this Jquery plugin, it's so cool. 使用这个Jquery插件,它太酷了。

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

You can use it like this way: 您可以像这样使用它:

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

The document.cookie property will return all the cookies. document.cookie属性将返回所有cookie。 While your indexOf will work, it will break if your cookies actual data contains 'PHPSESSID'. 虽然indexOf会起作用,但如果您的cookie实际数据包含“PHPSESSID”,它将会中断。 It will also match the following cookie 'MYPHPSESSIDIDIT', as it contains your cookie name. 它还将匹配以下cookie'MYPHPSESSIDIDIT',因为它包含您的cookie名称。

You could parse the cookies with the following function (not tested): 您可以使用以下函数解析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);
}

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM