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
相关产品推荐
相关产品推荐

