如何从 chrome.windows 创建的新弹出窗口中获取当前活动选项卡

Mar*_*son 3 javascript google-chrome google-chrome-extension reactjs

我将创建一个 chrome 扩展,它将弹出一个新窗口,通过这样做

chrome.windows.create({
  url: chrome.runtime.getURL("popup.html"),
  type: "popup",
});
Run Code Online (Sandbox Code Playgroud)

我的问题是来自“弹出窗口”,我想从“主窗口”访问活动选项卡,例如,我想从活动选项卡更改 DOM 的背景,在活动选项卡中单击显示弹出窗口的扩展。我希望这个问题不会令人困惑。:)

清单.json

{
 "name": "test",
 "description": "test",
 "version": "1.0.0",
 "manifest_version": 3,
 "background": {
   "service_worker": "background.js"
 },
 "permissions": ["storage", "activeTab", "scripting", "tabs"],
 "action": {
   "default_icon": {
     "16": "Icon-16.png",
     "32": "Icon-32.png",
     "48": "Icon-48.png",
     "128": "Icon-128.png"
    }
 },
"icons": {
   "16": "Icon-16.png",
   "32": "Icon-32.png",
   "48": "Icon-48.png",
   "128": "Icon-128.png"
 }
}
Run Code Online (Sandbox Code Playgroud)

在弹出窗口中,我有这个 onclick 函数

const onClick = async (e) => {
if (e && e.preventDefault) e.preventDefault();


const [tab] = await chrome.tabs.query({
  active: true,
  currentWindow: true,
});

chrome.scripting.executeScript({
  target: { tabId: tab.id },
  function: () => {
    chrome.storage.sync.get("color", ({ color }) => {
      document.body.style.backgroundColor = color;
    });
  },
});
Run Code Online (Sandbox Code Playgroud)

};

wOx*_*xOm 5

在创建窗口之前获取活动选项卡并将 id 作为 URL 参数传递。

扩展脚本:

async function openPopup() {
  const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
  await chrome.windows.create({
    url: `popup.html?${new URLSearchParams({
      tabId: tab.id,
    })}` ,
    type: 'popup',
  });
}
Run Code Online (Sandbox Code Playgroud)

弹出.html:

<script src="popup.js"></script>
Run Code Online (Sandbox Code Playgroud)

弹出.js:

const activeTabId = Number(new URLSearchParams(location.search).get('tabId'));
chrome.scripting.executeScript({ target: { tabId: activeTabId }, function: foo });
function foo() {
  console.log('injected foo');
}
Run Code Online (Sandbox Code Playgroud)