适用于Chrome扩展程序的BatteryStatus API无效

时间:2016-04-11 15:50:44

标签: javascript google-chrome-extension

我正在尝试为Chrome浏览器创建一个扩展程序,该扩展程序会显示系统的电池电量(以及其他内容)与BatteryStatusAPI. 起初我只是尝试使用简单的画布显示电池电量,但它似乎无法正常工作。

清单:

    {
    "manifest_version": 2,

    "name": "Battery",
    "description": "This extension shows the battery stats of the current device.",
    "version": "1.0",

    "browser_action": {
        "default_icon": "battery_full.png",
        "default_title": "Click Here!"
    },

    "background": {
        "scripts": ["icon_changer.js"]
    }
}

JavaScript的:

var battery;
navigator.getBattery()
    .then(function (b) {
        battery = b;
    }
);

function drawIcon() {
    var clockCanvas = document.createElement("canvas");
    clockCanvas.height = 19;
    clockCanvas.width = 19;

    var clockContext = clockCanvas.getContext("2d");
    clockContext.textAlign = "center";
    clockContext.textBaseline = "middle";
    clockContext.font = "9px Arial";
    clockContext.fillText(battery.level, 9, 10);

    chrome.browserAction.setIcon({
        imageData: clockContext.getImageData(0, 0, 19, 19)
    });
}

drawIcon();

您认为问题是什么?

1 个答案:

答案 0 :(得分:0)

您应该知道Navigator.getBattery().then(funcRef)funcRefnavigator.getBattery返回的电池promise得到解决时要调用的功能。由于异步性,当您致电drawIcon时,getBattery()可能尚未解决,因此funcRef将无法执行,这意味着battery未定义。

您应该在drawIcon内移动funcRef

var battery;
navigator.getBattery()
    .then(function (b) {
        battery = b;
        drawIcon();
    }
);

function drawIcon() {
    // Your logic here
}