diff --git a/src/libs/iframe.js b/src/libs/iframe.js new file mode 100644 index 0000000..3f5ed83 --- /dev/null +++ b/src/libs/iframe.js @@ -0,0 +1,7 @@ +export const isIframe = window.self !== window.top; + +export const sendIframeMsg = (action, args) => { + document.querySelectorAll("iframe").forEach((iframe) => { + iframe.contentWindow.postMessage({ action, args }, "*"); + }); +}; diff --git a/src/userscript.js b/src/userscript.js index da4271b..8cf1291 100644 --- a/src/userscript.js +++ b/src/userscript.js @@ -7,6 +7,8 @@ import { getSetting, getRules, matchRule, getFab } from "./libs"; import { Translator } from "./libs/translator"; import { trySyncAllSubRules } from "./libs/rules"; import { isGm } from "./libs/browser"; +import { MSG_TRANS_TOGGLE, MSG_TRANS_PUTRULE } from "./config"; +import { isIframe } from "./libs/iframe"; /** * 入口函数 @@ -23,17 +25,29 @@ import { isGm } from "./libs/browser"; return; } - // skip iframe - // if (window.self !== window.top) { - // return; - // } - // 翻译页面 const setting = await getSetting(); const rules = await getRules(); const rule = await matchRule(rules, document.location.href, setting); const translator = new Translator(rule, setting); + if (isIframe) { + // iframe + window.addEventListener("message", (e) => { + const action = e?.data?.action; + switch (action) { + case MSG_TRANS_TOGGLE: + translator.toggle(); + break; + case MSG_TRANS_PUTRULE: + translator.updateRule(e.data.args || {}); + break; + default: + } + }); + return; + } + // 浮球按钮 const fab = await getFab(); const $action = document.createElement("div"); @@ -57,11 +71,6 @@ import { isGm } from "./libs/browser"; ); - // skip iframe - if (window.self !== window.top) { - return; - } - // 注册菜单 if (isGm) { GM.registerMenuCommand( diff --git a/src/views/Popup/index.js b/src/views/Popup/index.js index 2a21fbb..40d36e8 100644 --- a/src/views/Popup/index.js +++ b/src/views/Popup/index.js @@ -18,6 +18,7 @@ import { OPT_LANGS_TO, OPT_STYLE_ALL, } from "../../config"; +import { sendIframeMsg } from "../../libs/iframe"; export default function Popup({ setShowPopup, translator: tran }) { const i18n = useI18n(); @@ -40,6 +41,7 @@ export default function Popup({ setShowPopup, translator: tran }) { await sendTabMsg(MSG_TRANS_TOGGLE); } else { tran.toggle(); + sendIframeMsg(MSG_TRANS_TOGGLE); } } catch (err) { console.log("[toggle trans]", err); @@ -55,6 +57,7 @@ export default function Popup({ setShowPopup, translator: tran }) { await sendTabMsg(MSG_TRANS_PUTRULE, { [name]: value }); } else { tran.updateRule({ [name]: value }); + sendIframeMsg(MSG_TRANS_PUTRULE, { [name]: value }); } } catch (err) { console.log("[update rule]", err);