applications-tracker/extensions/background-script.js

111 lines
2.7 KiB
JavaScript

/*browser.browserAction.onClicked.addListener(function (e) {
console.log("This is a nice test!", e);
});*/
browser.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
if (message.type === "REGISTER_INTEREST") {
let interestList =
(await browser.storage.local.get("interesetWindows"))
.interesetWindows ?? [];
// Already has interest!
if (interestList.includes(sender.tab.id)) {
return;
}
interestList.push(sender.tab.id);
await browser.storage.local.set({
interesetWindows: interestList,
});
return;
}
if (message.type === "GOT_INFO_R") {
// TODO then send this information back to that page
let interestList =
(await browser.storage.local.get("interesetWindows"))
.interesetWindows ?? [];
interestList.forEach((a) => {
browser.tabs.sendMessage(a, message);
});
return;
}
if (message.type === "R_GET_DATA_FROM_PAGE") {
let windowList = (await browser.storage.local.get("windows")).windows ?? [];
if (windowList.length !== 1) return;
const tab = await browser.tabs.get(windowList[0]);
browser.tabs.sendMessage(tab.id, {
type: "GET_DATA_FROM_PAGE",
});
return;
}
if (message.type !== "MY_GET_URL") return;
let windowList = (await browser.storage.local.get("windows")).windows ?? [];
if (windowList.length !== 1) {
browser.tabs.sendMessage(sender.tab.id, {
type: "MY_GET_URL_R",
error: "Invalid number of pages marked as target",
data: windowList,
});
return;
}
const tab = await browser.tabs.get(windowList[0]);
browser.tabs.sendMessage(tab.id, {
type: "GET_DATA_FROM_PAGE",
});
browser.tabs.sendMessage(sender.tab.id, {
type: "MY_GET_URL_R",
url: tab.url,
all_data: tab,
});
});
async function startup() {
await browser.storage.local.set({
windows: [],
interesetWindows: [],
});
// Clear the menus from the prev install
browser.menus.removeAll();
browser.menus.create({
id: "mark-page",
title: "Mark Page As the Glassdoor target",
contexts: ["all"],
});
browser.menus.create({
id: "mark-page-clear",
title: "Clear Marked Pages",
contexts: ["all"],
});
browser.menus.onClicked.addListener(async function (e, tab) {
let windowList =
(await browser.storage.local.get("windows")).windows ?? [];
console.log("test", e.menuItemId, e.menuItemId === "mark-page-clear");
if (e.menuItemId === "mark-page") {
console.log("marking page", tab);
if (windowList.includes(tab.id)) {
windowList = windowList.filter((a) => a !== tab.id);
} else {
windowList.push(tab.id);
}
} else if (e.menuItemId === "mark-page-clear") {
windowList = [];
console.log("clear");
}
await browser.storage.local.set({
windows: windowList,
});
});
}
browser.runtime.onInstalled.addListener(startup);