2

我有一个附加组件,我想在桌面上发出通知,但前提是用户正在积极使用计算机(例如,鼠标指针在任何地方移动,即不仅在浏览器窗口中)。

可以使用 WebExtensions 做到这一点吗?

我相信它会是这样的:

  • 脚本.js

    function Notify(id, title, message)
    {
        var props = {
            "type":    "basic",
            "title":   title,
            "iconUrl": "images/icon-128px.png",
            "message": message
        };
    
        var propsCopy = JSON.parse(JSON.stringify(props));
    
        propsCopy.requireInteraction = true;
    
        //Prevent exception in Firefox
        try {
            chrome.notifications.create(id, propsCopy, function() {});
        } catch (ee) {
            chrome.notifications.create(id, props, function() {});
        }
    }
    
  • 背景.js

    var standByNotifications = [];
    
    function registerNotification(id, title, message) {
        if ([user is inactive]) {
            standByNotifications.push({ "id": id, "title": title, "message": message });
        } else {
            Notify(id, title, message);
        }
    }
    
    setInterval(function() {
        if ([user is inactive] === false) {
            var tmp = standByNotifications.reverse();
    
            for (var i = tmp.length - 1; i >= 0; i--) {
                Notify(tmp[i].id, tmp[i].title, tmp[i].message);
            }
    
            standByNotifications = []; //Clear
        }
    }, 1000);
    
4

1 回答 1

3

Chrome 有一个专用的 APIchrome.idle来检测空闲状态。

chrome.idle.queryState(
  5 * 60, // seconds
  function(state) {
    if (state === "active") {
      // Computer not locked, user active in the last 5 minutes
    } else {
      // Computer is locked, or the user was inactive for 5 minutes
    }
  }
);

它还提供了一个事件 ,chrome.idle.onStateChanged以在状态更改时通知您。


WebExtensions将此 API 列为尚不支持(2016-07-21)。

  • queryState总是报告"active"状态。
  • onStateChanged不可用。
于 2016-07-21T15:23:25.023 回答