Skip to content

Instantly share code, notes, and snippets.

@freaktechnik
Created November 17, 2017 20:02
Show Gist options
  • Select an option

  • Save freaktechnik/b91a11ac9711e44c467478dfbd9e4163 to your computer and use it in GitHub Desktop.

Select an option

Save freaktechnik/b91a11ac9711e44c467478dfbd9e4163 to your computer and use it in GitHub Desktop.
Tab counter via canvas
"use strict";
const ICON_SIZE = 64;
const getIcon = async (count, size = ICON_SIZE) => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext('2d');
const {
bgColor,
color
} = await browser.storage.local.get({
bgColor: 'transparent',
color: '#000000'
});
ctx.fillStyle = bgColor;
ctx.fillRect(0, 0, size, size);
ctx.fillStyle = color;
ctx.textAlign = 'center';
const fontSize = size * 0.9;
ctx.font = `${fontSize}px system-ui, sans-serif`;
const center = size / 2;
ctx.fillText(count, center, center + (fontSize / 3), size);
return ctx.getImageData(0, 0, size, size);
};
const getTabCount = async (forWindow = null, includePinned = true) => {
const args = {};
if(forWindow !== null) {
args.windowId = forWindow;
}
if(!includePinned) {
args.pinned = false;
}
const tabs = await browser.tabs.query(args);
return tabs.length;
};
const setTabIcon = (count, icon, tabId) => {
await browser.browserAction.setIcon({
imageData: {
[ICON_SIZE]: icon
},
tabId
});
await browser.browserAction.setTitle({
title: count,
tabId
});
};
const setIcon = async () => {
const count = await getTabCount();
const icon = await getIcon(count);
await browser.browserAction.setIcon({
imageData: {
[ICON_SIZE]: icon
}
});
await browser.browserAction.setTitle({
title: count
});
};
browser.tabs.onCreated.addListener(setIcon);
browser.tabs.onRemoved.addListener(setIcon);
browser.tabs.onDetached.addListener(setIcon);
browser.runtime.onStartup.addListener(setIcon);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment