如何在一个回调函数动画chrome扩展图标

How to animate chrome extension icon in a callback function?

本文关键字:函数 回调 动画 chrome 图标 扩展 一个      更新时间:2023-09-26

这是我之前关于使用XMLHttpRequest()发布到我的书签应用程序的问题的后续。当我收到status 200 OK时,我想以某种方式在扩展图标中更改请求成功。我创建了另一个图标success_icon.png与反向颜色,我试图使新图标取代原来的图标,并逐渐变成原来的图标。我知道这将在我的回调函数内,但我不明白如何?这是我的background.html。谢谢!

chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.getSelected(null, function(tab) {
    tabId = tab.id;
    tabUrl = tab.url
    tabTitle = tab.title
var formData = new FormData();
formData.append("url", tabUrl);
formData.append("title", tabTitle);
formData.append("pitch", "this is a note");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
    if (xhr.readyState == 4) {
        if (xhr.status == 200)
            console.log("request 200-OK")
        else
        console.log("Error", xhr.statusText);
    }
};        
xhr.send(formData);

代码改编自eduardocereto的回答,但setTimeout不能正常工作:

if (xhr.readyState == 4 && xhr.status == 200) {
    console.log("request 200-OK");
    //chrome.browserAction.setIcon({path: '/success_icon.png'});
    chrome.browserAction.setBadgeText ( { text: "done" } );
    function resetBadge() {
        setTimeout (chrome.browserAction.setBadgeText( { text: "" } ), 10000);
    }
    resetBadge()
}

要动态更改图标,可以调用:

chrome.browserAction.setIcon({path: '/path/img/success_icon.png'})

创建渐隐效果不是那么容易,但是你可以使用<canvas>元素代替静态图像来设置图标。然后你可以用你想要的方式动画画布。

查看这篇关于如何将图像加载到画布并更改其不透明度的文章:

如何改变不透明度(alpha,透明度)的一个元素在画布元素已绘制后?

API参考:http://code.google.com/chrome/extensions/browserAction.html method-setIcon

使用setBadgeTextsetTimeout,你应该这样做:

chrome.browserAction.setBadgeText ( { text: "done" } );
setTimeout(function () {
    chrome.browserAction.setBadgeText( { text: "" } );
}, 1000);

我来到这里寻找一种方法来吸引一些注意到我的浏览器操作扩展…

这里有一些方便的代码来显示徽章:

function flashBadge(message, times, interval) {
    flash();
    function flash() {
        setTimeout(function () {
            if (times == 0) {
                chrome.browserAction.setBadgeText({text: message});
                return;
            }
            if (times % 2 == 0) {
                chrome.browserAction.setBadgeText({text: message});
            } else {
                chrome.browserAction.setBadgeText({text: ""});
            }
            times--;
            flash();
        }, interval);
    }
}