How to simulate document.cookie assignment in browser in Node environment?

when the following two lines of code are executed under the browser

document.cookie="a=1";

document.cookie="b=2";

console.log(document.cookie) // a=1; b=2

copy the code
and execute the following statement under Node

document={cookie:""};
document.cookie="a=1";
document.cookie="b=2";
console.log(document.cookie) //b=2

copy code
this is why, why does the document.cookie assignment under the browser not overwrite the old value?

< H2 > how to achieve the same effect under node. < / H2 >

the problem comes from the crawler I did to a website. The JS code is confused every time the site is opened. In many places in the JS code, the document.cookie is assigned
, but I intend to move the JS to execute under Node, where there is no document object itself. Just initialize one directly, only to find that there is a problem with the assignment.

Dec.27,2021

The

node environment does not have document, so the document object you declare is just a normal object
you can try this

function Document() {
    let cookie = ""
    Object.defineProperty(this, 'cookie', {
        get: function () {
            return cookie;
        },
        set: (a) => {
            cookie === "" ? cookie = a : cookie += `;${a}`
        }
    })
}
let document = new Document()

document.cookie = "a=1"
document.cookie = "b=2"

console.log(document.cookie)

however, if our crawlers encounter this kind of confusion, they usually use headless ~ ~ you can refer to

.
Menu