add a listener to click event of 'close sidepanel button'

251 views
Skip to first unread message

yoophoon wong

unread,
Jul 8, 2024, 8:39:54 PMJul 8
to Chromium Extensions
i want do something like update the sidepanel accessable status in indexedDB when i click the close button of sidepanelbutton.png
i've tried the window.onbeforeunload , and it seems not work,  what should i do to add a click event listener to this button
(one workaround is to add a new button to sidepanel document , i just want do something while click the close button directly)

woxxom

unread,
Jul 9, 2024, 3:30:12 AMJul 9
to Chromium Extensions, yoophoon wong
You can save the status into a synchronous DOM storage: window.onbeforeunload = () => localStorage.setItem('state', '0')
...and detect it in an already open offscreen document via window.onstorage = e => console.log(e.key);
...then delete the key from localStorage and add it to IndexedDB or you can just use localStorage via offscreen document instead of IndexedDB.

Alternatively, use a port:

// sidepanel.js
const port = chrome.runtime.connect({name: 'sidePanel'});
setInterval(() => port.postMessage('sidePanelPing'), 25e3); // keeping the background script alive while the side panel is open

// background.js
chrome.runtime.onConnect.addListener(port => {
  if (port.name === 'sidePanel') {
    console.log(port.sender);
    port.onDisconnect.addListener(() => {
      console.log('disconnected');
      // update IndexedDB here, optionally using port.sender if necessary
    });
  }
});

yoophoon wong

unread,
Jul 9, 2024, 9:14:18 PMJul 9
to Chromium Extensions, woxxom, yoophoon wong
thanks, the solution of my last question is also provided by you ❤  ❤  ❤  ❤     , and i tried the solution of this and it's nice to solve my problem. is there any doc about the reason that the API of indexedDB should not be used in the event callback function directly while synchronous API can, i want to learn about . 
Reply all
Reply to author
Forward
0 new messages