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.
sitepanel.js:

chrome.runtime.connect({ name: 'mySidepanel' });

The background script can add a listener and react accordingly.
background.js:

chrome.runtime.onConnect.addListener(function (port) {
  if (port.name === 'mySidepanel') {
    port.onDisconnect.addListener(async () => {
      console.log('Sidepanel closed.');
    });
  }
});

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

Your post must include a link to this post.

How does this work?
Write a response on your own website and include a link to this post. Then submit your response’s URL here. Your response may appear here after moderation. To update or remove it, edit or delete your original post and submit the same URL again. Learn more about Webmentions.