chrome 'setBadgeText' on pageAction

后端 未结 1 753
感情败类
感情败类 2021-02-10 09:39

I was looking how to set text to Page Action icon and found this example:

window.setInterval(function() {
    chrome.pageAction.setIcon({
        imageData: draw         


        
1条回答
  •  生来不讨喜
    2021-02-10 09:55

    The problem is that your canvas element is undefined (and undefined has no getContext() method). And the cause of the problem is that there is no canvas element in your background page, so you need to create it first.

    E.g.:

    // Replace that line:
    var canvas = document.getElementById('canvas');
    
    // With this line:
    var canvas = document.createElement('canvas');
    

    One more problem:

    The draw() function returns before the image is loaded (and its callback executed, drawing the image onto the canvas). I have modified the code, in order to ensure that the page-action image is set after the image is loaded:

    chrome.pageAction.onClicked.addListener(setPageActionIcon);
    
    function setPageActionIcon(tab) {
        var canvas = document.createElement('canvas');
        var img = document.createElement('img');
        img.onload = function () {
            var context = canvas.getContext('2d');
            context.drawImage(img, 0, 2);
            context.fillStyle = "rgba(255,0,0,1)";
            context.fillRect(10, 0, 19, 19);
            context.fillStyle = "white";
            context.font = "11px Arial";
            context.fillText("3", 0, 19);
    
            chrome.pageAction.setIcon({
                imageData: context.getImageData(0, 0, 19, 19),
                tabId:     tab.id
            });
        };
        img.src = "icon16.png";
    }
    
    Depending on how your going to use this, there might be more efficient ways (e.g. not having to load the image every time, but keep a loaded instance around).
    Should anyone be interested, **[here][1]** is my lame attempt to simulate a "native" Chrome badge.

    0 讨论(0)
提交回复
热议问题