Search code examples
javascriptreactjsgoogle-chromegoogle-chrome-extension

How to open Chrome Extension's side panel clicking a button inside the popup?


I have a chrome extension and want to use the recently added chrome.sidePanel API to open the side panel and show my chrome extension there when a user click a button inside the extension's popup.

I have tried the following code:

App.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 });
  });
}

background.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"
}
...

When I click on the button, I get the following error and the side panel doesn't open:

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


Solution

  • Solved this problem by using the following:

    const handleOpenSidePanel = () => {
      chrome.windows.getCurrent({ populate: true }, (window) => {
        (chrome as any).sidePanel.open({ windowId: window.id });
      });
    }