You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

BotD机器人检测结果如何正确保存至Cookie?

解决BotD检测结果存入Cookie的问题

问题根源:直接将JavaScript对象赋值给Cookie时,对象会被默认转换为[object Object]——这是JS对象默认toString()方法的返回值。要正确存储对象数据,需先将对象序列化为JSON字符串。

修改后的可运行代码

<script>
    // Initialize an agent at application startup, once per page/app.
    const botdPromise = import('https://openfpcdn.io/botd/v1').then((Botd) => Botd.load())
    // Get detection results when you need them.
    botdPromise
        .then((botd) => botd.detect())
        .then(result => {
            console.log(result)
            // 将检测结果序列化为JSON字符串后存入Cookie
            const botdJson = JSON.stringify(result);
            document.cookie = `botd=${botdJson}; path=/; secure; SameSite=strict`;
        })
        .catch((error) => console.error(error))
</script>

读取Cookie中检测结果的代码

如果之后需要取出存储的检测结果,可通过以下代码解析:

function getBotdCookie() {
    const cookies = document.cookie.split('; ');
    for (const cookie of cookies) {
        const [name, value] = cookie.split('=');
        if (name === 'botd') {
            return JSON.parse(value);
        }
    }
    return null;
}

// 使用示例
const botdResult = getBotdCookie();
console.log(botdResult);

额外提示

  • Cookie存储上限约4KB,BotD检测结果体积很小,完全满足存储要求。
  • 若需要Cookie在浏览器关闭后仍保留,可添加max-age属性,比如max-age=86400表示保留1天。

内容的提问来源于stack exchange,提问作者mkirk03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 15:48:30