pageAction 上的 chrome“setBadgeText”

2024-01-07

我正在寻找如何将文本设置为页面操作图标并找到了这个示例:

window.setInterval(function() {
    chrome.pageAction.setIcon({
        imageData: draw(10, 0),
        tabId: tabId
    });
}, 1000);

function draw(starty, startx) {
    var canvas = document.getElementById('canvas');
    var context = canvas.getContext('2d');
    var img = new Image();
    img.src = "icon_16.png"
    img.onload = function() {
        context.drawImage(img, 0, 2);
    }
    //context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "rgba(255,0,0,1)";
    context.fillRect(startx % 19, starty % 19, 10, 10);
    context.fillStyle = "white";
    context.font = "11px Arial";
    context.fillText("3", 0, 19);
    return context.getImageData(0, 0, 19, 19);
}

But after I include it to my eventPage.js it says Uncaught TypeError: Cannot call method 'getContext' of null . Then I googled for this error and found that I have to use getContext only after DOM is loaded. So I wrapped above code into jQuery .ready function but result was the same. enter image description here

所以我现在不知道错误在哪里以及我必须以何种方式进行搜索。


问题是你的canvas元素未定义(并且undefined has no getContext()方法)。而问题的原因是没有canvas元素在您的背景页面中,因此您需要首先创建它。

E.g.:

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

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

还有一个问题:

The draw()函数返回before图像已加载(并执行其回调,将图像绘制到画布上)。我修改了代码,以确保设置页面操作图像after图像已加载:

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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pageAction 上的 chrome“setBadgeText” 的相关文章