Display a Chrome desktop notification every day at specific time

泄露秘密 提交于 2021-01-29 07:17:08

问题


I'd like to write an extension that displays a desktop notification every day at a specified time. Having a quick look through the Chrome APIs, it seems like the only way to do this would be to:

  • create a background page for my extension,
  • use setInterval() with a sufficiently low resolution to not tax the CPU (even 5 min is fine),
  • when interval fires, check if the current time is after the desired time,
  • ensure that the user has not already been displayed the notification today.

(The details of the last step are irrelevant to my question, just put in to show I realize I need to prevent "flapping" of the notice).

This seems rather indirect and potentially expensive though; is there any way around this? Is the background page needed?

I suppose I could just call setTimeout() and only fire the event once (by calculating how long between now & desired time), then call it again after the notification is shown. For some reason that sounds more "brittle", though I'm not sure why...


回答1:


I think you will want the background page to do this smoothly. You can't use a content script because you need to keep the "state"/timer.

So when background page first loads (browser start) you work out the current time and the offset to the next notification time and setInterval to that exact interval. That way you won't need to poll every five minutes and/or work out if you've shown the message. You simply show it at the exact time required. This has to be far more efficient, effective and cleaner than polling. At notification you just reset the interval again.

Some sample functions here:

setTimeout but for a given time

From reading the above post and from a quick search on the net it appears that you should have no problem calling setInterval for an interval such as once a day. Calvin suggests 25 days!

That is how I would approach it.

EDIT: Since posting one thing that has sprung to mind is what happens if a PC gets hibernated for n hours? I need to test this myself for a similar project so I will update once I've had a chance to test this out.



来源:https://stackoverflow.com/questions/10032196/display-a-chrome-desktop-notification-every-day-at-specific-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!