2

I am using BotD for bot detection, and trying to figure out how to save the result into a cookie.

(I am sure this is simple, but im still trying to learn JS and stuck here)

Initial code:

<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))
        .catch((error) => console.error(error))
</script>

I tried:

<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)
            document.cookie ="botd="+result+"; path=/; secure; SameSite=strict";  
        })
        .catch((error) => console.error(error))
</script>

It prints correctly on console with "Object { bot: false }", but the cookie just says [object Object]

Any help with an example of how to get it to work would be appreciated.

Thanks,

mkirk03
  • 21
  • 2
  • cookies store text values, an Object is not text -JavaScript Object Notation is text notation for simple objects – Jaromanda X Feb 22 '23 at 00:46

2 Answers2

0

Cookies can only store string values. What you can do is to parse the object result you get into string by using JSON.stringfy method, and then store the string into cookies.

Example:

const object = {
  a: "apple",
  b: "boy",
  c: "cat",
  d: "dog",
  e: "eleplant",
  f: "fox",
  g: "goat",
  h: "hen",
  i: "iguana"
}

console.log(typeof object);
console.log(object);
//Parse Object to String
const string = JSON.stringify(object);
console.log(typeof string);
console.log(string);
//From here, store the string into cookies

Tips: Cookies does have a size limit. Thus, if the object is too complex/big, then it might not be able to store with cookies after stringify. You might need to look for other approach like localStorage.

Joshua Ooi
  • 1,139
  • 7
  • 18
0

You should change this line :

document.cookie ="botd="+result+"; path=/; secure; SameSite=strict";

to :

document.cookie ="botd="+JSON.stringify(result)+"; path=/; secure; SameSite=strict";

because document.cookie only accepts String (reference). So that JSON should be converted into String with JSON.stringify method

Jordy
  • 1,802
  • 2
  • 6
  • 25