0

As everybody knows, we can't persist data in popup window.

I have to recover the data when the popup window is opened again. But this data is not static data. It's a count value which is incremented by one per second.

So, for instance, if we close the popup window when the count value is 5 and reopen the popup window after 5 seconds, the count value should be 10. But now I get the initial value 0.

To handle this, I tried to use Sync storage.

Interval is running on the background script. And in the popup script, we just get the storage value and render.

But I think it's very bad practice to set storage value in every interval.

So Any solution to solve this problem?

I am currently thinking how to detect the popup window is closed.

If we detect the popup window is closed, then we can run the interval on the background script and get the count value from background script when popup window is opened again.

chrome.runtime.onConnect.addListener(function (externalPort) {
  externalPort.onDisconnect.addListener(function () {
    console.log("Disconnect");
  });
  console.log("Connect")
})

I try like above. But it didn't work.

Please help me how to detect the popup window is destroyed.

Also it would be great for me to let me know any other solution.

Thanks in advance.

Branch
  • 88
  • 7
  • Please use `localStorage`. – Norio Yamamoto Jun 08 '23 at 04:10
  • 1
    You can just save the date and time when the timer was started and when the popup opens, just compare the current date and time with that value to determine what value the timer should have. – Titus Jun 08 '23 at 04:10
  • 1
    [Example](https://stackoverflow.com/a/57854905). – wOxxOm Jun 08 '23 at 04:14
  • Thanks all. But looks like I again lost the data in background script when I close the chrome browser. How to overcome this? @wOxxOm – Branch Jun 08 '23 at 11:53
  • Thanks all. But looks like I again lost the data in background script when I close the chrome browser. How to overcome this? @Titus – Branch Jun 08 '23 at 11:53
  • Use chrome.storage.local as shown in the example. – wOxxOm Jun 08 '23 at 12:01
  • Thanks for clarifying. But any other solution with messaging? @wOxxOm – Branch Jun 08 '23 at 12:09
  • Messaging would waste resources to keep the background script running, see [Persistent Service Worker in Chrome Extension](https://stackoverflow.com/a/66618269) – wOxxOm Jun 08 '23 at 12:32
  • Thanks. @wOxxOm. If you don't mind, can we establish some connection through discord, slack or email? Any one would be OK. I really look forward to get more help from you regarding extension development. Looks like you are a great expert. My mail is waterredlover@gmail.com. – Branch Jun 08 '23 at 13:35
  • Sorry @wOxxOm. But could you let me know how to detect when browser is closed in background script? I tried to use ```chrome.windows.onRemoved```. But it doesn't work well. – Branch Jun 08 '23 at 13:47

0 Answers0