doulongti5932 2014-01-18 19:43
浏览 69
已采纳

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

I have set a session in PHP, which is creating a cookie: PHPSESSID... I can detect this in Chrome & Opera by using document.cookie. However in Forefox, document.cookie also returns cookies set on the page by other domains, e.g. Google Analytics.

In PHP I am setting the sessions like:

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. 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.

  • 写回答

2条回答 默认 最新

  • dpd3447 2014-01-18 20:14
    关注

    The document.cookie property will return all the cookies. While your indexOf will work, it will break if your cookies actual data contains 'PHPSESSID'. It will also match the following cookie 'MYPHPSESSIDIDIT', as it contains your cookie name.

    You could parse the cookies with the following function (not tested):

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?