Skip to content

sidePanel API: sidePanel.close() and sidePanel.toggle() #521

@fregante

Description

@fregante

The sidePanel can be opened via chrome.sidePanel.open() but the API isn't symmetrical, there is no .close() API.

It would also be useful (maybe even more so) to just .toggle() the sidebar instead, using any trigger other than the action click, for example:

  • menus.onClick
  • any <button> added on the page
  • keyboard shortcuts
  • command palettes in the content script

Alternative to chrome.sidePanel.close() (✅ it works)

As @dotproto pointed out, the sidebar can close itself via window.close(), so in other contexts you would have to set up messaging.

// background.js
function open () {
  chrome.sidePanel.open()
}
function close() {
  chrome.runtime.sendMessage('closeSidePanel');
}
// sidepanel.js
chrome.runtime.onMessage.addListener(message => {
  // Might not be as easy if there are multiple side panels open
  if (message === 'closeSidePanel') {
    window.close();
  }
})

You can also use chrome.sidePanel.setOptions({enabled: false}) but that has undesired side effects (it removes it from the side panels list)

Alternative to chrome.sidePanel.toggle() (⛔️ it doesn't work)

This is more complicated because there's no easy way to determine whether the sidebar is open, so you'd have to add another listener and hope that this delay won't cause you to lose the user gesture permission:

Warning

I just tested this and it doesn't work: Error: sidePanel.open() may only be called in response to a user gesture

function isSidePanelOpen() {
  try {
    return await chrome.runtime.sendMessage('isSidePanelOpen');
  } catch {
    return false
  }
}
async function toggle() {
  if (await isSidePanelOpen()) {
    chrome.runtime.sendMessage('closeSidePanel');
  } else {
    chrome.sidePanel.open()
  }
}
// sidepanel.js
chrome.runtime.onMessage.addListener(message => {
  // Might not be as easy if there are multiple side panels open
  if (message === 'isSidePanelOpen') {
    return true
  }

  if (message === 'closeSidePanel') {
    window.close();
  }
})

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementEnhancement or change to an existing featuretopic: sidebarDiscussions related to the sidebarAction and sidePanel APIs

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions