Files
kiss-translator/src/userscript.js

65 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-08-05 20:11:02 +08:00
import React from "react";
import ReactDOM from "react-dom/client";
2023-08-05 23:56:16 +08:00
import Action from "./views/Action";
import createCache from "@emotion/cache";
import { CacheProvider } from "@emotion/react";
2023-08-05 20:11:02 +08:00
2023-08-05 15:32:51 +08:00
import { getRules, matchRule } from "./libs";
import { getSetting } from "./libs";
import { transPool } from "./libs/pool";
import { Translator } from "./libs/translator";
/**
* 入口函数
*/
(async () => {
2023-08-05 20:11:02 +08:00
// 设置页面
2023-08-06 21:12:01 +08:00
if (
2023-08-09 18:02:18 +08:00
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE_DEV) ||
2023-08-07 11:53:44 +08:00
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE) ||
document.location.href.includes(process.env.REACT_APP_OPTIONSPAGE2)
2023-08-06 21:12:01 +08:00
) {
2023-08-09 17:33:51 +08:00
window.unsafeWindow.GM = window.GM;
window.unsafeWindow.GM_xmlhttpRequest = window.GM_xmlhttpRequest;
window.unsafeWindow.GM_setValue = window.GM_setValue;
window.unsafeWindow.GM_getValue = window.GM_getValue;
window.unsafeWindow.GM_deleteValue = window.GM_deleteValue;
2023-08-09 18:02:18 +08:00
window.unsafeWindow.APP_NAME = process.env.REACT_APP_NAME;
2023-08-05 20:11:02 +08:00
return;
}
2023-08-09 14:57:51 +08:00
// skip iframe
2023-08-06 22:01:47 +08:00
if (window.self !== window.top) {
return;
}
2023-08-09 14:57:51 +08:00
// 翻译页面
const { fetchInterval, fetchLimit } = await getSetting();
transPool.update(fetchInterval, fetchLimit);
const rules = await getRules();
const rule = matchRule(rules, document.location.href);
const translator = new Translator(rule);
2023-08-09 14:57:51 +08:00
// 浮球按钮
const $action = document.createElement("div");
$action.setAttribute("id", "kiss-translator");
2023-08-05 23:56:16 +08:00
document.body.parentElement.appendChild($action);
const shadowContainer = $action.attachShadow({ mode: "open" });
const emotionRoot = document.createElement("style");
const shadowRootElement = document.createElement("div");
shadowContainer.appendChild(emotionRoot);
shadowContainer.appendChild(shadowRootElement);
const cache = createCache({
key: "css",
prepend: true,
container: emotionRoot,
});
ReactDOM.createRoot(shadowRootElement).render(
<React.StrictMode>
<CacheProvider value={cache}>
2023-08-09 14:57:51 +08:00
<Action translator={translator} />
</CacheProvider>
</React.StrictMode>
);
2023-08-05 15:32:51 +08:00
})();