From 9d4c596b4b2db519a7092f78ad32f84edfec3f81 Mon Sep 17 00:00:00 2001 From: Gabe Yuan Date: Thu, 14 Mar 2024 16:28:32 +0800 Subject: [PATCH] fix: getCurTab --- src/libs/msg.js | 30 +++++++++++++++++++----------- src/views/Popup/index.js | 4 ++-- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/libs/msg.js b/src/libs/msg.js index 46dba20..a060560 100644 --- a/src/libs/msg.js +++ b/src/libs/msg.js @@ -1,5 +1,22 @@ import { browser } from "./browser"; +/** + * 获取当前tab信息 + * @returns + */ +export const getCurTab = async () => { + const [tab] = await browser.tabs.query({ + active: true, + lastFocusedWindow: true, + }); + return tab; +}; + +export const getCurTabId = async () => { + const tab = await getCurTab(); + return tab.id; +}; + /** * 发送消息给background * @param {*} action @@ -16,15 +33,6 @@ export const sendBgMsg = (action, args) => * @returns */ export const sendTabMsg = async (action, args) => { - const tabs = await browser.tabs.query({ active: true, currentWindow: true }); - return browser.tabs.sendMessage(tabs[0].id, { action, args }); -}; - -/** - * 获取当前tab信息 - * @returns - */ -export const getTabInfo = async () => { - const tabs = await browser.tabs.query({ active: true, currentWindow: true }); - return tabs[0]; + const tabId = await getCurTabId(); + return browser.tabs.sendMessage(tabId, { action, args }); }; diff --git a/src/views/Popup/index.js b/src/views/Popup/index.js index 9c3f4f9..d11daa3 100644 --- a/src/views/Popup/index.js +++ b/src/views/Popup/index.js @@ -5,7 +5,7 @@ import MenuItem from "@mui/material/MenuItem"; import FormControlLabel from "@mui/material/FormControlLabel"; import Switch from "@mui/material/Switch"; import Button from "@mui/material/Button"; -import { sendBgMsg, sendTabMsg, getTabInfo } from "../../libs/msg"; +import { sendBgMsg, sendTabMsg, getCurTab } from "../../libs/msg"; import { browser } from "../../libs/browser"; import { isExt } from "../../libs/client"; import { useI18n } from "../../hooks/I18n"; @@ -83,7 +83,7 @@ export default function Popup({ setShowPopup, translator: tran }) { try { let href = window.location.href; if (!tran) { - const tab = await getTabInfo(); + const tab = await getCurTab(); href = tab.url; } const newRule = { ...rule, pattern: href.split("/")[2] };