Files
kiss-translator/src/background.js

69 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-07-20 13:45:41 +08:00
import browser from "webextension-polyfill";
import {
MSG_FETCH,
MSG_FETCH_LIMIT,
DEFAULT_SETTING,
DEFAULT_RULES,
2023-07-31 15:08:51 +08:00
DEFAULT_SYNC,
2023-07-20 13:45:41 +08:00
STOKEY_SETTING,
STOKEY_RULES,
2023-07-31 15:08:51 +08:00
STOKEY_SYNC,
2023-07-20 13:45:41 +08:00
CACHE_NAME,
} from "./config";
import { fetchData, setFetchLimit } from "./libs/fetch";
import storage from "./libs/storage";
import { getSetting } from "./libs";
2023-07-31 15:08:51 +08:00
import { syncAll } from "./libs/sync";
2023-07-20 13:45:41 +08:00
/**
* 插件安装
*/
browser.runtime.onInstalled.addListener(() => {
console.log("onInstalled");
storage.trySetObj(STOKEY_SETTING, DEFAULT_SETTING);
storage.trySetObj(STOKEY_RULES, DEFAULT_RULES);
2023-07-31 15:08:51 +08:00
storage.trySetObj(STOKEY_SYNC, DEFAULT_SYNC);
2023-07-20 13:45:41 +08:00
});
/**
* 浏览器启动
*/
browser.runtime.onStartup.addListener(async () => {
console.log("onStartup");
2023-07-31 03:10:09 +08:00
// 同步数据
2023-07-31 15:08:51 +08:00
await syncAll();
2023-07-31 03:10:09 +08:00
// 清除缓存
2023-07-20 13:45:41 +08:00
const { clearCache } = await getSetting();
if (clearCache) {
caches.delete(CACHE_NAME);
}
});
/**
* 监听消息
*/
browser.runtime.onMessage.addListener(
({ action, args }, sender, sendResponse) => {
switch (action) {
case MSG_FETCH:
fetchData(args.input, args.init)
.then((data) => {
sendResponse({ data });
})
.catch((error) => {
sendResponse({ error: error.message });
});
break;
case MSG_FETCH_LIMIT:
setFetchLimit(args.limit);
sendResponse({ data: "ok" });
break;
default:
sendResponse({ error: `message action is unavailable: ${action}` });
}
return true;
}
);