cuticle/background.js

67 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2021-09-24 19:08:59 +00:00
console.log("hi");
2021-09-25 05:59:26 +00:00
// ran on keyboard shortcut
// configure your own in manifest.json
// dont forget to hijack for {next,prev}Tab!
2021-09-24 23:28:16 +00:00
chrome.commands.onCommand.addListener(async (command) => {
2021-09-24 19:08:59 +00:00
switch(command) {
2021-09-25 05:59:26 +00:00
case "pip": {
2021-11-18 21:26:57 +00:00
run(await getTab(), "content.js");
2021-09-24 19:08:59 +00:00
break;
2021-09-25 05:59:26 +00:00
}
case "nextTab":
case "prevTab": {
const tab = await getTab();
const tabs = await chrome.tabs.query({ currentWindow: true });
const index = tabs.findIndex(i => i.id === tab);
const groups = await chrome.tabGroups.query({ windowId: tab.windowId });
const next = (index + (command === "prevTab" ? -1 : 1) + tabs.length) % tabs.length;
chrome.tabs.update(tabs[next].id, { active: true });
for(let group of groups) {
if(group.id === tabs[next].groupId) continue;
chrome.tabGroups.update(group.id, { collapsed: true });
}
break;
}
2021-09-24 19:08:59 +00:00
}
});
2021-11-17 22:39:21 +00:00
// auto hide shelf
let downloads = 0;
chrome.downloads.onCreated.addListener(() => {
downloads++;
chrome.downloads.setShelfEnabled(true);
});
chrome.downloads.onChanged.addListener(async (item) => {
if(!item.state) return;
if(["complete", "interrupted"].includes(item.state.current)) downloads--;
2021-11-17 22:42:25 +00:00
if(downloads === 0)
2021-11-17 22:39:21 +00:00
chrome.downloads.setShelfEnabled(false);
});
// clean up downloads occasionally
// setInterval(async () => {
// const dl = chrome.downloads;
// const query = { startedAfter: Date.now() - 1000 * 60 * 10 };
// const items = await dl.search(query);
// for(let item of items) dl.removeFile(item.id);
// }, 1000 * 60 * 5);
2021-09-25 05:59:26 +00:00
// get the current tab id
2021-09-24 23:28:16 +00:00
async function getTab() {
2021-09-24 19:08:59 +00:00
const queryOptions = { active: true, currentWindow: true };
2021-11-17 22:42:25 +00:00
const [tab] = await chrome.tabs.query(queryOptions);
2021-09-24 19:08:59 +00:00
if(!tab) return;
2021-09-24 23:28:16 +00:00
return tab.id;
}
2021-09-25 05:59:26 +00:00
// run a script on a tab
2021-09-24 23:28:16 +00:00
async function run(tabId, file) {
2021-11-17 22:42:25 +00:00
chrome.scripting.executeScript({
2021-09-24 23:28:16 +00:00
target: { tabId },
2021-09-24 19:08:59 +00:00
files: [file],
});
}