Files
kiss-translator/src/background.js

76 lines
1.7 KiB
JavaScript
Raw Normal View History

2023-08-05 18:15:01 +08:00
import browser from "webextension-polyfill";
2023-07-20 13:45:41 +08:00
import {
MSG_FETCH,
2023-08-10 11:55:40 +08:00
MSG_FETCH_LIMIT,
2023-08-11 16:48:09 +08:00
MSG_FETCH_CLEAR,
2023-07-20 13:45:41 +08:00
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 storage from "./libs/storage";
import { getSetting } from "./libs";
2023-07-31 15:08:51 +08:00
import { syncAll } from "./libs/sync";
2023-08-10 11:55:40 +08:00
import { fetchData, fetchPool } from "./libs/fetch";
2023-07-20 13:45:41 +08:00
/**
* 插件安装
*/
browser.runtime.onInstalled.addListener(() => {
2023-08-17 13:27:22 +08:00
console.log("KISS Translator onInstalled");
2023-07-20 13:45:41 +08:00
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 () => {
2023-08-17 13:27:22 +08:00
console.log("browser 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:
2023-08-10 11:55:40 +08:00
const { input, init, opts } = args;
fetchData(input, init, opts)
2023-07-20 13:45:41 +08:00
.then((data) => {
sendResponse({ data });
})
.catch((error) => {
sendResponse({ error: error.message });
});
break;
2023-08-10 11:55:40 +08:00
case MSG_FETCH_LIMIT:
const { interval, limit } = args;
fetchPool.update(interval, limit);
sendResponse({ data: "ok" });
break;
2023-08-11 16:48:09 +08:00
case MSG_FETCH_CLEAR:
fetchPool.clear();
sendResponse({ data: "ok" });
break;
2023-07-20 13:45:41 +08:00
default:
sendResponse({ error: `message action is unavailable: ${action}` });
}
return true;
}
);