如何通过单击弹出窗口内的按钮来打开 Chrome 扩展程序的侧面板?

问题描述 投票:0回答:1

我有一个 chrome 扩展程序,想要使用最近添加的 chrome.sidePanel API 打开侧面板,并在用户单击扩展程序弹出窗口内的按钮时在其中显示我的 chrome 扩展程序。

我尝试过以下代码:

应用程序.tsx

const handleOpenSidePanel = async () => {
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    const currentTabId = tabs[0].id;
    chrome.runtime.sendMessage({ type: 'openSidePanel', tabId: currentTabId });
  });
}

背景.js

chrome.runtime.onMessage.addListener((message, tab) => {
  if (message.type === "openSidePanel") {
    chrome.sidePanel.open({ windowId: tab.windowId});
  }
});

manifest.json

"permissions": [
  "sidePanel",
  "tabs"
],
"side_panel": {
  "default_path": "index.html"
}
...

当我单击按钮时,出现以下错误并且侧面板未打开:

Uncaught (in promise) Error: At least one of "tabId" and "windowId" must be provided

javascript reactjs google-chrome google-chrome-extension
1个回答
0
投票

你有两个选择,

  1. 单击操作栏中的图标时打开侧面板(在这种情况下不需要弹出窗口)

添加到service-worker.js:

chrome.sidePanel
          .setPanelBehavior({ openPanelOnActionClick: true })
          .catch((error) => console.error(error));
  1. 从弹出窗口打开用户交互侧面板(单击按钮)

在这种情况下,您的清单版本 3 具有以下属性:

添加到manifest.json:

  "background": {
    "service_worker": "service-worker.js"
  },
  "side_panel": {
    "default_path": "sidepanel-global.html"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "permissions": ["sidePanel"],

然后弹出窗口上有一个按钮(id =“openSidePanel”),单击该按钮时会向服务工作线程发送一条消息。

添加到popup.js:

document.getElementById('openSidePanel').addEventListener('click', function() {
        chrome.runtime.sendMessage({action: 'open_side_panel'});
    });

Service Worker 会收到消息,但在此之前,您需要确保将 Windows 选项卡信息传递给 Service Worker:

添加到service-worker.js:

// to find the windowId of the active tab
let windowId;
chrome.tabs.onActivated.addListener(function (activeInfo) {
  windowId = activeInfo.windowId;
});

// to receive messages from popup script
chrome.runtime.onMessage.addListener((message, sender) => {
  (async () => {
    if (message.action === 'open_side_panel') {
      chrome.sidePanel.open({ windowId: windowId });
    }
  })();
});

在这里您可以找到更多选项:Chrome 侧面板为什么 sendMessage 不传递 tabId

© www.soinside.com 2019 - 2024. All rights reserved.