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.