Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: Added the ability to save objects and arrays in cookies using JSON (skin.js) #4085

Merged
merged 4 commits into from
Jul 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions web/skins/classic/js/skin.js
Original file line number Diff line number Diff line change
Expand Up @@ -761,7 +761,19 @@ function setButtonState(element_id, btnClass) {
}
}

function isJSON(str) {
if (typeof str !== 'string') return false;
try {
const result = JSON.parse(str);
const type = Object.prototype.toString.call(result);
return type === '[object Object]' || type === '[object Array]'; // We only pass objects and arrays
} catch (e) {
return false; // This is also not JSON
}
};

function setCookie(name, value, seconds) {
var newValue = (typeof value === 'string') ? value : JSON.stringify(value);
let expires = "";
if (seconds) {
const date = new Date();
Expand All @@ -771,18 +783,28 @@ function setCookie(name, value, seconds) {
// 2147483647 is 2^31 - 1 which is January of 2038 to avoid the 32bit integer overflow bug.
expires = "; max-age=2147483647";
}
document.cookie = name + "=" + (value || "") + expires + "; path=/; samesite=strict";
document.cookie = name + "=" + (newValue || "") + expires + "; path=/; samesite=strict";
}

/*
* If JSON is stored in cookies, the function will return an array or object of values.
*/
function getCookie(name) {
var nameEQ = name + "=";
var result = null;
var ca = document.cookie.split(';');
for (var i=0; i < ca.length; i++) {
if (result) break;
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
if (c.indexOf(nameEQ) == 0) {
result = c.substring(nameEQ.length, c.length);
break;
}
}
return null;
if (isJSON(result)) result = JSON.parse(result);

return result;
}

function delCookie(name) {
Expand Down