使用WebExtensions检测用户桌面不活动

时间:2016-07-21 15:12:01

标签: javascript google-chrome-extension firefox-webextensions

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

可以使用WebExtensions吗?

我相信会是这样的:

  • 的script.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() {});
        }
    }
    
  • background.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);
    

1 个答案:

答案 0 :(得分:3)

Chrome有一个专用API,chrome.idle,用于检测空闲状态。

    Configuration config = getResources().getConfiguration();
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    if (!config.locale.equals(Locale.SIMPLIFIED_CHINESE)){
        config.locale = Locale.SIMPLIFIED_CHINESE;
        getResources().updateConfiguration(config, metrics);
    } else {
        config.locale = Locale.ENGLISH;
        getResources().updateConfiguration(config, metrics);
    }
    recreate();

它还提供了一个事件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 } } ); ,以便在状态发生变化时通知您。

WebExtensions list this API as not yet supported(2016-07-21)。

  • chrome.idle.onStateChanged始终报告queryState州。
  • "active"不可用。