1
0
mirror of https://github.com/kkapsner/CanvasBlocker synced 2024-12-22 12:50:36 +01:00

Switch to asych/await where useful

This commit is contained in:
kkapsner 2019-12-28 23:23:55 +01:00
parent 372ee755f7
commit 10413a89c3
11 changed files with 269 additions and 349 deletions

View File

@ -83,12 +83,10 @@ async function translate(language){
return data; return data;
} }
translate(language).then(function(data){ (async function(){
"use strict"; "use strict";
return saveTranslation(language, data); const data = await translate(language);
}).catch(function(error){
"use strict";
console.error(error); saveTranslation(language, data);
}); }());

View File

@ -114,11 +114,10 @@
} }
return lists[type]; return lists[type];
}; };
scope.appendTo = function appendToList(type, entry){ scope.appendTo = async function appendToList(type, entry){
const oldValue = settings[type + "List"]; const oldValue = settings[type + "List"];
return settings.set(type + "List", oldValue + (oldValue? ",": "") + entry).then(function(){ await settings.set(type + "List", oldValue + (oldValue? ",": "") + entry);
return updateList(type); return updateList(type);
});
}; };
scope.update = updateList; scope.update = updateList;
scope.updateAll = function updateAllLists(){ scope.updateAll = function updateAllLists(){

View File

@ -13,10 +13,11 @@
} }
let settings = false; let settings = false;
scope.setSettings = function(realSettings){ scope.setSettings = async function(realSettings){
if (!settings){ if (!settings){
settings = realSettings; settings = realSettings;
return settings.loaded.then(scope.clearQueue); await settings.loaded;
return scope.clearQueue();
} }
else { else {
warning("logging: Settings can only be set once."); warning("logging: Settings can only be set once.");

View File

@ -14,7 +14,7 @@
const registerSettingsContentScript = (function(){ const registerSettingsContentScript = (function(){
let unregisterSettingsContentScript = function(){}; let unregisterSettingsContentScript = function(){};
let lastRegistering; let lastRegistering;
return function registerSettingsContentScript(){ return async function registerSettingsContentScript(){
logging.message("Register content script for the settings."); logging.message("Register content script for the settings.");
logging.verbose("Unregister old content script, if present."); logging.verbose("Unregister old content script, if present.");
unregisterSettingsContentScript(); unregisterSettingsContentScript();
@ -23,7 +23,7 @@
data[def.name] = def.get(); data[def.name] = def.get();
}); });
lastRegistering = data; lastRegistering = data;
browser.contentScripts.register({ const api = await browser.contentScripts.register({
matches: ["<all_urls>"], matches: ["<all_urls>"],
matchAboutBlank: true, matchAboutBlank: true,
allFrames: true, allFrames: true,
@ -52,19 +52,16 @@
} }
}(${JSON.stringify(data)}))` }(${JSON.stringify(data)}))`
}] }]
}).then(function(api){
logging.verbose("Content script registered.");
if (data !== lastRegistering){
logging.verbose("Multiple content scripts registered at once. Remove unnecessary one.");
api.unregister();
}
else {
unregisterSettingsContentScript = api.unregister;
}
return;
}).catch(function(error){
logging.warning("Unable to register content script:", error);
}); });
logging.verbose("Content script registered.");
if (data !== lastRegistering){
logging.verbose("Multiple content scripts registered at once. Remove unnecessary one.");
api.unregister();
}
else {
unregisterSettingsContentScript = api.unregister;
}
}; };
}()); }());
@ -79,7 +76,7 @@
persistentRndStorage.init(); persistentRndStorage.init();
logging.message("register non port message listener"); logging.message("register non port message listener");
browser.runtime.onMessage.addListener(function(data){ browser.runtime.onMessage.addListener(async function(data){
logging.notice("got data without port", data); logging.notice("got data without port", data);
const keys = Object.keys(data); const keys = Object.keys(data);
if (data["canvasBlocker-new-domain-rnd"]){ if (data["canvasBlocker-new-domain-rnd"]){
@ -105,13 +102,9 @@
} }
} }
logging.notice("pass the message to the tabs"); logging.notice("pass the message to the tabs");
browser.tabs.query({}).then(function(tabs){ const tabs = await browser.tabs.query({});
tabs.forEach(function(tab){ tabs.forEach(function(tab){
browser.tabs.sendMessage(tab.id, data); browser.tabs.sendMessage(tab.id, data);
});
return;
}).catch(function(error){
logging.warning("Unable to get browser tabs:", error);
}); });
}); });
@ -190,10 +183,9 @@
} }
// mobile default settings // mobile default settings
mobile.ifMobile(function(){ mobile.ifMobile(async function(){
return browser.storage.local.get().then(mobile.applyMobileDefaults).catch(function(error){ const settings = await browser.storage.local.get();
logging.error("Unable to set mobile default values:", error); mobile.applyMobileDefaults(settings);
});
}); });
}); });

View File

@ -15,31 +15,29 @@
const settings = require("./settings"); const settings = require("./settings");
const settingDefinitions = require("./settingDefinitions"); const settingDefinitions = require("./settingDefinitions");
scope.isMobile = function isMobile(){ scope.isMobile = async function isMobile(){
// todo: proper mobile check (e.g. over browser.runtime.getBrowserInfo()) and no feature check // todo: proper mobile check (e.g. over browser.runtime.getBrowserInfo()) and no feature check
return Promise.resolve( return !browser.pageAction ||
!browser.pageAction ||
!browser.pageAction.show || !browser.pageAction.show ||
!browser.pageAction.openPopup !browser.pageAction.openPopup
); ;
}; };
scope.ifMobile = function ifMobile(ifCallback, elseCallback){ scope.ifMobile = async function ifMobile(ifCallback, elseCallback){
return scope.isMobile().then(function(isMobile){ const isMobile = await scope.isMobile();
if (isMobile){ if (isMobile){
return ifCallback(); return ifCallback();
} }
else if (elseCallback){ else if (elseCallback){
return elseCallback(); return elseCallback();
} }
else { else {
return false; return false;
} }
});
}; };
scope.applyMobileDefaults = function applyMobileDefaults(storage = false){ scope.applyMobileDefaults = async function applyMobileDefaults(storage = false){
return Promise.all(settingDefinitions.filter(function(definition){ await Promise.all(settingDefinitions.filter(function(definition){
return definition.hasOwnProperty("mobileDefaultValue") && ( return definition.hasOwnProperty("mobileDefaultValue") && (
!storage || !storage ||
!storage.hasOwnProperty(definition.name) !storage.hasOwnProperty(definition.name)

View File

@ -163,16 +163,12 @@
}); });
}; };
settings.on("showNotifications", function({newValue}){ settings.on("showNotifications", async function({newValue}){
if (!newValue){ if (!newValue){
logging.message("notifications were disabled -> hide all page actions"); logging.message("notifications were disabled -> hide all page actions");
browser.tabs.query({}).then(function(tabs){ const tabs = await browser.tabs.query({});
tabs.forEach(function(tab){ tabs.forEach(function(tab){
browser.pageAction.hide(tab.id); browser.pageAction.hide(tab.id);
});
return;
}).catch(function(error){
logging.warning("Unable to get browser tabs:", error);
}); });
} }
}); });
@ -180,20 +176,16 @@
browser.tabs.onRemoved.addListener(function(tabId){ browser.tabs.onRemoved.addListener(function(tabId){
tabsData.delete(tabId); tabsData.delete(tabId);
}); });
settings.on("displayBadge", function({newValue}){ settings.on("displayBadge", async function({newValue}){
if (!newValue){ if (!newValue){
logging.message("badge was disabled -> hide all badges"); logging.message("badge was disabled -> hide all badges");
if (browser.browserAction.setBadgeText){ if (browser.browserAction.setBadgeText){
browser.tabs.query({}).then(function(tabs){ const tabs = await browser.tabs.query({});
tabs.forEach(function(tab){ tabs.forEach(function(tab){
browser.browserAction.setBadgeText({ browser.browserAction.setBadgeText({
tabId: tab.id, tabId: tab.id,
text: "" text: ""
});
}); });
return;
}).catch(function(error){
logging.warning("Unable to get browser tabs:", error);
}); });
} }
} }

View File

@ -89,17 +89,13 @@
}; };
}(); }();
browser.windows.onRemoved.addListener(function(){ browser.windows.onRemoved.addListener(async function(){
browser.windows.getAll().then(function(windows){ const windows = await browser.windows.getAll();
if (windows.every(function(window){ if (windows.every(function(window){
return !window.incognito; return !window.incognito;
})){ })){
clearIncognito(); clearIncognito();
} }
return;
}).catch(function(error){
logging.warning("Unable to get browser windows:", error);
});
}); });
function registerTimeout(){ function registerTimeout(){
@ -117,14 +113,10 @@
} }
} }
} }
function broadcast(data){ async function broadcast(data){
browser.tabs.query({}).then(function(tabs){ const tabs = await browser.tabs.query({});
tabs.forEach(function(tab){ tabs.forEach(function(tab){
browser.tabs.sendMessage(tab.id, data); browser.tabs.sendMessage(tab.id, data);
});
return;
}).catch(function(error){
logging.warning("Unable to get browser tabs:", error);
}); });
} }
function clearIncognito(){ function clearIncognito(){

View File

@ -129,24 +129,24 @@
} }
return true; return true;
}; };
const storeValue = function storeValue(newValue){ const storeValue = async function storeValue(newValue){
logging.verbose("Trying to store new value for %s", name, newValue); logging.verbose("Trying to store new value for %s", name, newValue);
settings[name] = newValue; settings[name] = newValue;
if (!settingDefinition.transient){ if (!settingDefinition.transient){
const storeObject = {}; const storeObject = {};
storeObject[name] = newValue; storeObject[name] = newValue;
const promise = browser.storage.local.set(storeObject); try {
promise.then(function(){ await browser.storage.local.set(storeObject);
logging.verbose("New value stored for %s:", name, newValue); logging.verbose("New value stored for %s:", name, newValue);
return; }
}).catch(function(error){ catch (error){
logging.error("Unable to store new value for %s:", name, newValue, error); logging.error("Unable to store new value for %s:", name, newValue, error);
}); throw error;
return promise; }
} }
else { else {
logging.warning("Transient setting %s cannot be stored.", name); logging.warning("Transient setting %s cannot be stored.", name);
return Promise.reject("Transient setting " + name + " cannot be stored."); throw "Transient setting " + name + " cannot be stored.";
} }
}; };

View File

@ -35,23 +35,18 @@
logging.notice("send message to main script"); logging.notice("send message to main script");
extension.message.send({"canvasBlocker-clear-domain-rnd": true}); extension.message.send({"canvasBlocker-clear-domain-rnd": true});
}, },
clearPersistentRndForContainer: function(){ clearPersistentRndForContainer: async function(){
browser.contextualIdentities.query({}).then(function(identities){ const identities = await browser.contextualIdentities.query({});
return modal.select( const identity = await modal.select(
extension.getTranslation("clearPersistentRndForContainer_title"), extension.getTranslation("clearPersistentRndForContainer_title"),
identities.map(function(identity){ identities.map(function(identity){
return { return {
name: `${identity.name} (${identity.cookieStoreId})`, name: `${identity.name} (${identity.cookieStoreId})`,
object: identity object: identity
}; };
}) })
); );
}).then(function(identity){ extension.message.send({"canvasBlocker-clear-container-rnd": identity.cookieStoreId});
extension.message.send({"canvasBlocker-clear-container-rnd": identity.cookieStoreId});
return;
}).catch(function(error){
logging.warning("Unable to clear persistent rnd for container:", error);
});
}, },
inspectSettings: function(){ inspectSettings: function(){
logging.verbose("open settings inspection"); logging.verbose("open settings inspection");
@ -96,9 +91,9 @@
logging.verbose("open whitelist inspection"); logging.verbose("open whitelist inspection");
window.open("whitelist.html", "_blank"); window.open("whitelist.html", "_blank");
}, },
loadSettings: function(){ loadSettings: async function(){
logging.verbose("load settings"); logging.verbose("load settings");
new Promise(function(resolve, reject){ const text = await new Promise(function(resolve, reject){
const input = document.createElement("input"); const input = document.createElement("input");
input.type = "file"; input.type = "file";
input.addEventListener("change", function(){ input.addEventListener("change", function(){
@ -114,32 +109,27 @@
} }
}); });
input.click(); input.click();
}).then(function(text){ });
return JSON.parse(text); let json = JSON.parse(text);
}).then(function(json){ while (settingsMigration.transitions.hasOwnProperty(json.storageVersion)){
while (settingsMigration.transitions.hasOwnProperty(json.storageVersion)){ let oldVersion = json.storageVersion;
let oldVersion = json.storageVersion; json = settingsMigration.transitions[json.storageVersion](json);
json = settingsMigration.transitions[json.storageVersion](json); if (oldVersion === json.storageVersion){
if (oldVersion === json.storageVersion){ break;
break;
}
} }
const keys = Object.keys(json); }
keys.forEach(function(key){ const keys = Object.keys(json);
const setting = settings.getDefinition(key); keys.forEach(function(key){
if (!settings){ const setting = settings.getDefinition(key);
throw new Error("Unknown setting " + key + "."); if (!settings){
} throw new Error("Unknown setting " + key + ".");
if (!setting.fixed && setting.invalid(json[key])){ }
throw new Error("Invalid value " + json[key] + " for " + key + "."); if (!setting.fixed && setting.invalid(json[key])){
} throw new Error("Invalid value " + json[key] + " for " + key + ".");
}); }
keys.forEach(function(key){ });
settings[key] = json[key]; keys.forEach(function(key){
}); settings[key] = json[key];
return;
}).catch(function(error){
alert(error);
}); });
}, },
resetSettings: async function(){ resetSettings: async function(){
@ -165,18 +155,7 @@
} }
}; };
new Promise(function(resolve){ browser.tabs.getCurrent().then(function(tab){
const port = browser.runtime.connect();
port.onMessage.addListener(function(data){
if (data.hasOwnProperty("tabId")){
logging.notice("my tab id is", data.tabId);
port.disconnect();
resolve(data.tabId);
}
});
}).then(function(tabId){
return browser.tabs.get(tabId);
}).then(function(tab){
document.querySelector("head title").textContent = extension.getTranslation("options_title"); document.querySelector("head title").textContent = extension.getTranslation("options_title");
let head = document.createElement("header"); let head = document.createElement("header");
document.body.insertBefore(head, document.body.firstChild); document.body.insertBefore(head, document.body.firstChild);
@ -236,7 +215,7 @@
linkDiv.appendChild(link); linkDiv.appendChild(link);
head.appendChild(linkDiv); head.appendChild(linkDiv);
} }
return; return undefined;
}).catch(function(error){ }).catch(function(error){
logging.warning("Unable to identify tab:", error); logging.warning("Unable to identify tab:", error);
}); });
@ -569,7 +548,7 @@
return response.json(); return response.json();
}).then(function(manifest){ }).then(function(manifest){
version.textContent = "Version " + manifest.version; version.textContent = "Version " + manifest.version;
return; return manifest.version;
}).catch(function(error){ }).catch(function(error){
version.textContent = "Unable to get version: " + error; version.textContent = "Unable to get version: " + error;
}); });
@ -578,7 +557,7 @@
settings.onloaded(function(){ settings.onloaded(function(){
const reCaptchaEntry = "^https://www\\.google\\.com/recaptcha/api2/(?:b?frame|anchor).*$"; const reCaptchaEntry = "^https://www\\.google\\.com/recaptcha/api2/(?:b?frame|anchor).*$";
const {url: urlContainer} = settings.getContainers(); const {url: urlContainer} = settings.getContainers();
settings.on("protectWindow", function({newValue}){ settings.on("protectWindow", async function({newValue}){
if (newValue){ if (newValue){
const urlValue = urlContainer.get(); const urlValue = urlContainer.get();
const matching = urlValue.filter(function(entry){ const matching = urlValue.filter(function(entry){
@ -591,20 +570,16 @@
matching[0].protectWindow matching[0].protectWindow
) )
){ ){
modal.confirm( const addException = await modal.confirm(
extension.getTranslation("protectWindow_askReCaptchaException"), extension.getTranslation("protectWindow_askReCaptchaException"),
{ {
node: document.querySelector("[data-storage-name=protectWindow]"), node: document.querySelector("[data-storage-name=protectWindow]"),
selector: ".settingRow .content" selector: ".settingRow .content"
} }
).then(function(addException){ );
if (addException){ if (addException){
settings.set("protectWindow", false, reCaptchaEntry); settings.set("protectWindow", false, reCaptchaEntry);
} }
return;
}).catch(function(error){
logging.warning("Error while adding reCaptcha exception:", error);
});
} }
} }
}); });

View File

@ -1,7 +1,7 @@
/* This Source Code Form is subject to the terms of the Mozilla Public /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function(){ (async function(){
"use strict"; "use strict";
const extension = require("../lib/extension"); const extension = require("../lib/extension");
@ -76,8 +76,8 @@
if (settingsList.childNodes.length){ if (settingsList.childNodes.length){
const button = document.createElement("button"); const button = document.createElement("button");
button.textContent = extension.getTranslation("apply"); button.textContent = extension.getTranslation("apply");
button.addEventListener("click", function(){ button.addEventListener("click", async function(){
Promise.all(Object.keys(preset).map(function(settingName){ await Promise.all(Object.keys(preset).map(function(settingName){
const value = preset[settingName]; const value = preset[settingName];
if ((typeof value) === "object"){ if ((typeof value) === "object"){
return Promise.all(Object.keys(value).map(function(url){ return Promise.all(Object.keys(value).map(function(url){
@ -87,12 +87,9 @@
else { else {
return settings.set(settingName, value); return settings.set(settingName, value);
} }
})).then(function(){ }));
window.location.reload();
return; window.location.reload();
}).catch(function(error){
logging.warning("Unable to apply preset:", error);
});
}); });
container.appendChild(button); container.appendChild(button);
} }
@ -100,20 +97,7 @@
return container; return container;
} }
Promise.all([ function fitContentToWindowSize(){
settings.loaded,
fetch("presets.json").then(function(data){
return data.json();
})
// eslint-disable-next-line no-unused-vars
]).then(function([settingsLoaded, presets]){
Object.keys(presets).map(function(presetName){
return buildPresetGui(presetName, presets[presetName]);
}).forEach(function(node){
document.body.appendChild(node);
});
// fit content to the window size
if (window.innerHeight > document.body.getBoundingClientRect().bottom){ if (window.innerHeight > document.body.getBoundingClientRect().bottom){
const computedStyle = window.getComputedStyle(document.body); const computedStyle = window.getComputedStyle(document.body);
const availableHeight = window.innerHeight - parseFloat(computedStyle.marginBottom); const availableHeight = window.innerHeight - parseFloat(computedStyle.marginBottom);
@ -141,10 +125,7 @@
document.body.style.fontSize = fontSize + "px"; document.body.style.fontSize = fontSize + "px";
} }
} }
return; }
}).catch(function(error){
logging.warning("Unable to setup presets:", error);
});
document.querySelector("head title").textContent = extension.getTranslation("presets_title"); document.querySelector("head title").textContent = extension.getTranslation("presets_title");
let head = document.createElement("header"); let head = document.createElement("header");
@ -195,4 +176,17 @@
introduction.className = "introduction"; introduction.className = "introduction";
introduction.textContent = extension.getTranslation("presets_introduction"); introduction.textContent = extension.getTranslation("presets_introduction");
head.appendChild(introduction); head.appendChild(introduction);
const [settingsLoaded, presets] = await Promise.all([
settings.loaded,
(await fetch("presets.json")).json()
]);
Object.keys(presets).map(function(presetName){
return buildPresetGui(presetName, presets[presetName]);
}).forEach(function(node){
document.body.appendChild(node);
});
fitContentToWindowSize();
}()); }());

View File

@ -1,7 +1,7 @@
/* This Source Code Form is subject to the terms of the Mozilla Public /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function(){ (async function(){
"use strict"; "use strict";
const extension = require("../lib/extension"); const extension = require("../lib/extension");
@ -37,12 +37,9 @@
{ {
name: "disableNotifications", name: "disableNotifications",
isIcon: true, isIcon: true,
callback: function(){ callback: async function(){
settings.set("showNotifications", false).then(function(){ await settings.set("showNotifications", false);
return window.close(); window.close();
}).catch(function(error){
logging.warning("Unable to disable notifications:", error);
});
} }
} }
], ],
@ -55,26 +52,24 @@
{ {
name: "ignorelist", name: "ignorelist",
isIcon: true, isIcon: true,
callback: function({domain, urls}){ callback: async function({domain, urls}){
return domainOrUrlPicker( const choice = await domainOrUrlPicker(
domain, domain,
urls, urls,
extension.getTranslation("selectIgnore"), extension.getTranslation("selectIgnore"),
extension.getTranslation("inputIgnoreURL") extension.getTranslation("inputIgnoreURL")
).then(function(choice){ );
if (choice){
return settings.set("showNotifications", false, choice); if (choice){
} await settings.set("showNotifications", false, choice);
return false; }
}).then(function(){ window.close();
return window.close();
});
} }
}, },
{ {
name: "whitelist", name: "whitelist",
isIcon: true, isIcon: true,
callback: function({domain, urls, api}){ callback: async function({domain, urls, api}){
const whitelistingSettings = { const whitelistingSettings = {
all: {name: "blockMode", value: "allow"}, all: {name: "blockMode", value: "allow"},
canvas: {name: "protectedCanvasPart", value: "nothing"}, canvas: {name: "protectedCanvasPart", value: "nothing"},
@ -85,67 +80,56 @@
windows: {name: "protectWindow", value: false}, windows: {name: "protectWindow", value: false},
screen: {name: "protectScreen", value: false}, screen: {name: "protectScreen", value: false},
}; };
return domainOrUrlPicker( const choice = await domainOrUrlPicker(
domain, domain,
urls, urls,
extension.getTranslation("selectWhitelist"), extension.getTranslation("selectWhitelist"),
extension.getTranslation("inputWhitelistURL") extension.getTranslation("inputWhitelistURL")
).then(function(choice){ );
if ( let setting = whitelistingSettings.all;
api && if (
whitelistingSettings[api] api &&
){ whitelistingSettings[api]
// eslint-disable-next-line promise/no-nesting ){
return modalChoice( setting = whitelistingSettings[await modalChoice(
extension.getTranslation("selectWhitelistScope"), extension.getTranslation("selectWhitelistScope"),
[ [
{ {
text: extension.getTranslation("whitelistOnlyAPI") text: extension.getTranslation("whitelistOnlyAPI")
.replace( .replace(
/\{api\}/g, /\{api\}/g,
extension.getTranslation("section_" + api + "-api") extension.getTranslation("section_" + api + "-api")
), ),
value: api value: api
}, },
{ {
text: extension.getTranslation("whitelistAllAPIs"), text: extension.getTranslation("whitelistAllAPIs"),
value: "all" value: "all"
} }
] ]
).then(function(selection){ )];
return {choice, setting: whitelistingSettings[selection]}; }
}); if (choice){
} await settings.set(setting.name, setting.value, choice);
else { }
return {choice, setting: whitelistingSettings.all};
} window.close();
}).then(function({choice, setting}){
if (choice){
return settings.set(setting.name, setting.value, choice);
}
return false;
}).then(function(){
return window.close();
});
} }
}, },
{ {
name: "whitelistTemporarily", name: "whitelistTemporarily",
isIcon: true, isIcon: true,
callback: function({domain, urls}){ callback: async function({domain, urls}){
return domainOrUrlPicker( const choice = await domainOrUrlPicker(
domain, domain,
urls, urls,
extension.getTranslation("selectSessionWhitelist"), extension.getTranslation("selectSessionWhitelist"),
extension.getTranslation("inputSessionWhitelistURL") extension.getTranslation("inputSessionWhitelistURL")
).then(function(choice){ );
if (choice){ if (choice){
return lists.appendTo("sessionWhite", choice); await lists.appendTo("sessionWhite", choice);
} }
return false; window.close();
}).then(function(){
return window.close();
});
} }
}, },
{ {
@ -193,7 +177,7 @@
}); });
} }
function domainOrUrlPicker(domain, urls, selectText, urlInputText){ async function domainOrUrlPicker(domain, urls, selectText, urlInputText){
const choices = Array.from(urls).map(function(url){ const choices = Array.from(urls).map(function(url){
return { return {
text: url, text: url,
@ -203,99 +187,94 @@
if (domain){ if (domain){
choices.unshift(domain); choices.unshift(domain);
} }
return modalChoice( const choice = await modalChoice(
selectText, selectText,
choices choices
).then(function(choice){ );
if (choice.startsWith("^")){ if (choice.startsWith("^")){
return modalPrompt( return modalPrompt(
urlInputText, urlInputText,
choice choice
); );
} }
else { else {
return choice; return choice;
} }
});
} }
Promise.all([ const values = await Promise.all([
browser.tabs.query({active: true, currentWindow: true}), browser.tabs.query({active: true, currentWindow: true}),
settings.loaded settings.loaded
]).then(function(values){ ]);
const tabs = values[0]; const tabs = values[0];
if (!tabs.length){ if (!tabs.length){
throw new Error("noTabsFound"); throw new Error("noTabsFound");
}
else if (tabs.length > 1){
logging.error(tabs);
throw new Error("tooManyTabsFound");
}
registerActionButtons();
registerDomainActions();
registerNotificationActions();
const tab = tabs[0];
extension.message.on(function(data){
if (data["canvasBlocker-notificationCounter"]){
const url = new URL(data.url);
Object.keys(data["canvasBlocker-notificationCounter"]).forEach(function(key){
domainNotification(
url,
key,
data["canvasBlocker-notificationCounter"][key].count,
data["canvasBlocker-notificationCounter"][key].api
);
});
} }
else if (tabs.length > 1){ if (
logging.error(tabs); Array.isArray(data["canvasBlocker-notifications"]) &&
throw new Error("tooManyTabsFound"); data["canvasBlocker-notifications"].length
} ){
logging.message("got notifications");
registerActionButtons(); const notifications = data["canvasBlocker-notifications"];
let i = 0;
registerDomainActions(); const length = notifications.length;
const tick = window.setInterval(function(){
registerNotificationActions(); if (i >= length){
window.clearInterval(tick);
const tab = tabs[0]; }
extension.message.on(function(data){ else {
if (data["canvasBlocker-notificationCounter"]){ let delta = 0;
const url = new URL(data.url); for (; delta < 20 && i + delta < length; delta += 1){
Object.keys(data["canvasBlocker-notificationCounter"]).forEach(function(key){ let notification = notifications[i + delta];
domainNotification( logging.verbose(notification);
url, if (settings.ignoredAPIs[notification.api]){
key, continue;
data["canvasBlocker-notificationCounter"][key].count,
data["canvasBlocker-notificationCounter"][key].api
);
});
}
if (
Array.isArray(data["canvasBlocker-notifications"]) &&
data["canvasBlocker-notifications"].length
){
logging.message("got notifications");
const notifications = data["canvasBlocker-notifications"];
let i = 0;
const length = notifications.length;
const tick = window.setInterval(function(){
if (i >= length){
window.clearInterval(tick);
}
else {
let delta = 0;
for (; delta < 20 && i + delta < length; delta += 1){
let notification = notifications[i + delta];
logging.verbose(notification);
if (settings.ignoredAPIs[notification.api]){
continue;
}
logging.verbose(notification);
notification.url = new URL(notification.url);
domainNotification(
notification.url,
notification.messageId,
0,
notification.api
).addNotification(new Notification(notification));
} }
i += delta; logging.verbose(notification);
notification.url = new URL(notification.url);
domainNotification(
notification.url,
notification.messageId,
0,
notification.api
).addNotification(new Notification(notification));
} }
}, 1); i += delta;
} }
}); }, 1);
logging.message("request notifications from tab", tab.id); }
browser.tabs.sendMessage(
tab.id,
{
"canvasBlocker-sendNotifications": tab.id
}
);
logging.notice("waiting for notifications");
return;
}).catch(function(error){
error(error);
}); });
logging.message("request notifications from tab", tab.id);
browser.tabs.sendMessage(
tab.id,
{
"canvasBlocker-sendNotifications": tab.id
}
);
logging.notice("waiting for notifications");
}()); }());