UNPKG

@binance/fingerprint

Version:

binance web fingerprint

86 lines (85 loc) 2.83 kB
import { STORE_KEY } from "../constant"; import { deleteCookie } from "./cookie"; import { safeJsonParse } from "./json"; import { isClient } from "./is"; var memoryStorage = {}; var isSupportSession = function() { return typeof sessionStorage !== "undefined"; }; var isSupportLocal = function() { return typeof localStorage !== "undefined"; }; function isString(value) { return Object.prototype.toString.call(value) === "[object String]"; } export var setLocalStorage = function(key, value) { var options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; if (!isSupportLocal()) return; if (!options.ttl) { return localStorage.setItem(key, value); } // set ttl return localStorage.setItem(key, JSON.stringify({ value: value, expire: new Date().getTime() + options.ttl })); }; export var getLocalStorage = function(key) { if (!isSupportLocal()) return; var originValue = localStorage.getItem(key); var data = safeJsonParse(originValue) || {}; // expire is null if (!data.expire) return originValue; // has an expiration time and does not expire if (data.expire && data.expire > new Date().getTime()) return data.value; return null; }; export var setCacheDevice = function(value) { if (!isClient) return; var name = STORE_KEY; var storeVal = JSON.stringify(value); // cookie deleteCookie(name); // localStorage if (isSupportLocal()) { setLocalStorage(name, storeVal); } // sessionStorage if (isSupportSession()) { sessionStorage.setItem(name, storeVal); } // memoryStorage memoryStorage[STORE_KEY] = storeVal; }; export var getCacheDevice = function() { if (!isClient) return {}; var name = STORE_KEY; var deviceStr = null; // from memoryStorage if (!deviceStr) { deviceStr = memoryStorage[STORE_KEY]; } // from localStorage if (!deviceStr && isSupportLocal()) { deviceStr = getLocalStorage(name) || null; } // from sessionStorage if (!deviceStr && isSupportSession()) { deviceStr = sessionStorage.getItem(name) || null; } var device = safeJsonParse(deviceStr) || {}; if (isString(device)) { console.log("device need decodeURIComponent"); // eslint-disable-next-line max-len // device maybe like "%7B%22e5ea997c6c44ee66e59b20f1946236c6%22%3A%7B%22date%22%3A1733398786698%2C%22value%22%3A%22%22%7D%7D" // The specific reason has not been found yet try { device = safeJsonParse(decodeURIComponent(device)); } catch (error) { console.log("device need decodeURIComponent error", error); } } // sync to other storage deviceStr && setCacheDevice(device); return device; };