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

qfe3c7zg  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(397)

我将创建一个chrome扩展,它将弹出一个新窗口

chrome.windows.create({
  url: chrome.runtime.getURL("popup.html"),
  type: "popup",
});

我的问题来自“弹出窗口”,我想从“主窗口”访问活动选项卡,例如,我想从我单击显示弹出窗口的扩展的活动选项卡更改dom的背景。我希望这个问题不会令人困惑
manifest.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"
 }
}

在弹出窗口中,我有这个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;
    });
  },
});

};

d6kp6zgx

d6kp6zgx1#

在创建窗口之前获取活动选项卡,并将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',
  });
}

popup.html:

<script src="popup.js"></script>

popup.js:

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

相关问题