Search code examples
addeventlistenerfirefox-addon-webextensionsfirefox-sidebar

Listen to Firefox WebExtension sidebar closing


I am working on a WebExtension using the sidebar.

When the sidebar is open, the extension performs some operations on the current tab. When it is closed, I want to revert these operations.

Is this possible? I didn't see methods like browser.sidebarAction.addEventListener.


Solution

  • I adapted GnxR's idea in the following:

    extension/page/sidebar.html:

    <!DOCTYPE html>
    <html>
        <body>
            <div id="panel"></div>
            <script src="static.js"></script>
        </body>
    </html>
    

    extension/page/static.js:

    window.addEventListener('beforeunload', (event) => {
      console.log('Sidebar will be closed!');
      // Do stuff
    });
    window.addEventListener('pagehide', (event) => {
      console.log('Sidebar is hidden!');
      // Do stuff
    });
    window.addEventListener('unload', (event) => {
      console.log('Sidebar is unloaded!');
      // Do stuff
    });
    

    When closing the extension (both from the cross bar and programmatically), I get the following in the browser console:

    Sidebar is hiding! static.js:6:3
    Sidebar is unloaded! static.js:10:3 
    

    Therefore it seems that both pagehide and unload events can be used, but that beforeunload is never fired.