DEV Community

Latz
Latz

Posted on

Chrome side panel: Simulate close event

The new side panel in Chrome does not contain a close event, which could come handy if you want to clean up stuff after the panel has been closed.

You can simulate the event by opening a permanent connection between the side panel and the background script. This connection fires an onDisconnect event if the side panel gets closed.

sidepanel.js:

chrome.runtime.connect({ name: 'mySidepanel' });
Enter fullscreen mode Exit fullscreen mode

The background script can add a listener and react accordingly:

background.js:

chrome.runtime.onConnect.addListener((port) => {
  if (port.name === 'mySidepanel') {
    port.onDisconnect.addListener(() => {
      console.log('Sidepanel closed.');
    });
  }
});
Enter fullscreen mode Exit fullscreen mode

Note that switching between panels is not sufficient, the event will only fire if the side panel is fully closed.

Top comments (0)