This commit is contained in:
xu_yanfeng 2025-02-13 16:12:25 +08:00
parent 851c50a5f3
commit e7283964b4

View File

@ -14,17 +14,18 @@ class Config {
async init() { async init() {
try { try {
let str: string = ""; let str: string = "";
if (this.isChromeBackgroundEnv()) { if (this.isNormalWebEnv()) {
str = localStorage.getItem(this.key);
} else if (this.isChromeBackgroundEnv()) {
const ret = await chrome.storage.local.get(this.key); const ret = await chrome.storage.local.get(this.key);
if (ret && ret[this.key]) { if (ret && ret[this.key]) {
str = ret[this.key] as string; str = ret[this.key] as string;
} }
} else {
str = localStorage.getItem(this.key);
} }
if (str) { if (str) {
const ret = JSON.parse(str) as MirrorInfo[]; const ret = JSON.parse(str) as MirrorInfo[];
if (ret) { if (ret) {
this.data = [];
ret.forEach((el) => { ret.forEach((el) => {
this.data.push({ name: el.name, time: el.time }); this.data.push({ name: el.name, time: el.time });
}); });
@ -37,6 +38,9 @@ class Config {
private isChromeBackgroundEnv() { private isChromeBackgroundEnv() {
return typeof chrome !== "undefined" && typeof chrome.storage !== "undefined" && typeof chrome.storage.local !== "undefined"; return typeof chrome !== "undefined" && typeof chrome.storage !== "undefined" && typeof chrome.storage.local !== "undefined";
} }
private isNormalWebEnv() {
return typeof localStorage !== "undefined";
}
async save(name: string, time: number) { async save(name: string, time: number) {
const ret = this.data.find((el) => el.name === name); const ret = this.data.find((el) => el.name === name);
if (ret) { if (ret) {
@ -45,10 +49,11 @@ class Config {
this.data.push({ name: name, time: time } as MirrorInfo); this.data.push({ name: name, time: time } as MirrorInfo);
} }
const saveString = JSON.stringify(this.data); const saveString = JSON.stringify(this.data);
if (this.isChromeBackgroundEnv()) {
await chrome.storage.local.set({ [this.key]: saveString }); if (this.isNormalWebEnv()) {
} else {
localStorage.setItem(this.key, saveString); localStorage.setItem(this.key, saveString);
} else if (this.isChromeBackgroundEnv()) {
await chrome.storage.local.set({ [this.key]: saveString });
} }
} }
getTime(url: string) { getTime(url: string) {