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条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大