各位好~
我知道可以用document.cookie=去設定cookie!
不過我是用extension去得到的,所以有一大串好幾個,我在想是不是要搞個function去寫!?
舉例一下大概長這樣:
[
{
"domain": ".xxxxxxx.cc",
"expirationDate": 1707798734,
"hostOnly": false,
"httpOnly": false,
"name": "__gads",
"path": "/",
"sameSite": "unspecified",
"secure": false,
"session": false,
"storeId": "0",
"value": "ID=8sdgsfdgdfsg353-fsdgfsdgsfdgfsdgsfgw",
"id": 1
},
{
"domain": ".cdfgdfdfgd.cc",
"expirationDate": 1707798734,
"hostOnly": false,
"httpOnly": false,
"name": "__gpi",
"path": "/",
"sameSite": "unspecified",
"secure": false,
"session": false,
"storeId": "0",
"value": "UID=0gdfgdfg8d:T=1674102734:RT=1674124997:S=ALNI_dfgtScvL_wJgUVJQl-tVHA",
"id": 2
},
]
想請問該怎麼撰寫一個function,
讓我一次可以灌這麼大串(原本的data可能還有六串)的cookie呢??
謝謝各位前輩們~~
參考看看
function setCookies(cookiesArray) {
cookiesArray.forEach(function(cookie) {
document.cookie = `${cookie.name}=${cookie.value}; expires=${new Date(cookie.expirationDate * 1000).toUTCString()}; path=${cookie.path}; domain=${cookie.domain};`;
});
}
將要設置的cookie數組作為參數傳遞給函數即可:
setCookies([
{
"domain": ".xxxxxxx.cc",
"expirationDate": 1707798734,
"hostOnly": false,
"httpOnly": false,
"name": "__gads",
"path": "/",
"sameSite": "unspecified",
"secure": false,
"session": false,
"storeId": "0",
"value": "ID=8sdgsfdgdfsg353-fsdgfsdgsfdgfsdgsfgw",
"id": 1
},
{
"domain": ".cdfgdfdfgd.cc",
"expirationDate": 1707798734,
"hostOnly": false,
"httpOnly": false,
"name": "__gpi",
"path": "/",
"sameSite": "unspecified",
"secure": false,
"session": false,
"storeId": "0",
"value": "UID=0gdfgdfg8d:T=1674102734:RT=1674124997:S=ALNI_dfgtScvL_wJgUVJQl-tVHA",
"id": 2
},
]);
用 map 不好嗎?
不過我不太理解這個 array 是怎麼來的就是
例如我這邊得到的 document.cookie 是
_gcl_au=1.1.1334778127.1672340871; _ga=GA1.1.1416806687.1651757520; _ga_6182VBHV8Y=GS1.1.1672341045.1.1.1672341208.0.0.0; __utmz=147059567.1674535345.157.131.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utma=147059567.2060415170.1645350932.1674537149.1674673523.159; __utmc=147059567; __utmt=1; __utmb=147059567.24.10.1674673523; XSRF-TOKEN=eyJpdiI6ImN...(略)...lYzJkOTk5Y2YwYTZjZDkxIn0%3D
總感覺
const getDocumentCookie = arrayAbove => (
arrayAbove
.map(i => `${i.name}=${i.value}`)
.join('; '));
之類的東西可以解決?