Migration to MV3

This commit is contained in:
Kevin R
2023-11-11 17:49:00 +01:00
parent 92e43b7f61
commit b55b6af007
11 changed files with 96 additions and 105 deletions

View File

@@ -727,3 +727,9 @@ function start() {
["blocking"] ["blocking"]
); );
} }
// TODO: Must be asked after install
browser.permissions.request({
permissions: ["webRequest", "webRequestBlocking", "tabs", "scripting", "webNavigation"],
origins: ["<all_urls>"],
});

View File

@@ -48,9 +48,9 @@ function increaseBadged(quiet = false, request) {
checkOSAndroid().then((res) => { checkOSAndroid().then((res) => {
if (!res) { if (!res) {
if (storage.badgedStatus && !quiet) { if (storage.badgedStatus && !quiet) {
browser.browserAction.setBadgeText({text: (badges[tabId]).counter.toString(), tabId: tabId}).catch(handleError); browser.action.setBadgeText({text: (badges[tabId]).counter.toString(), tabId: tabId}).catch(handleError);
} else { } else {
browser.browserAction.setBadgeText({text: "", tabId: tabId}).catch(handleError); browser.action.setBadgeText({text: "", tabId: tabId}).catch(handleError);
} }
} }
}); });

View File

@@ -22,8 +22,9 @@
* and based on: https://github.com/mdn/webextensions-examples/tree/master/context-menu-copy-link-with-types * and based on: https://github.com/mdn/webextensions-examples/tree/master/context-menu-copy-link-with-types
*/ */
function contextMenuStart() { browser.runtime.onInstalled.addListener(contextMenuStart);
if(storage.contextMenuEnabled) {
function contextMenuStart(details) {
browser.contextMenus.create({ browser.contextMenus.create({
id: "copy-link-to-clipboard", id: "copy-link-to-clipboard",
title: translate("clipboard_copy_link"), title: translate("clipboard_copy_link"),
@@ -33,25 +34,17 @@ function contextMenuStart() {
browser.contextMenus.onClicked.addListener((info, tab) => { browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "copy-link-to-clipboard") { if (info.menuItemId === "copy-link-to-clipboard") {
const url = pureCleaning(info.linkUrl); const url = pureCleaning(info.linkUrl);
const code = "copyToClipboard(" +
JSON.stringify(url)+");";
browser.tabs.executeScript({ browser.scripting.executeScript({
code: "typeof copyToClipboard === 'function';", target: {
}).then((results) => { tabId: tab.id,
if (!results || results[0] !== true) { allFrames: true
return browser.tabs.executeScript(tab.id, { },
file: "/external_js/clipboard-helper.js", func: (text) => navigator.clipboard.writeText(text),
}).catch(handleError); args: [
} url
}).then(() => { ]
return browser.tabs.executeScript(tab.id, {
code,
});
}).catch((error) => {
console.error("Failed to copy text: " + error);
}); });
} }
}); });
} }
}

View File

@@ -17,16 +17,17 @@
*/ */
/*jshint esversion: 6 */ /*jshint esversion: 6 */
/* /*
* This script is responsible for listen on history changes. * This script is responsible for listen on history changes.
* This technique is often used to inject tracking code into the location bar, * This technique is often used to inject tracking code into the location bar,
* because all feature events will use the updated URL. * because all feature events will use the updated URL.
*/ */
function historyListenerStart() {
if(storage.historyListenerEnabled) {
browser.webNavigation.onHistoryStateUpdated.addListener(historyCleaner); browser.webNavigation.onHistoryStateUpdated.addListener(historyCleaner);
}
function historyListenerStart() {
} }
/** /**
@@ -37,15 +38,24 @@ function historyListenerStart() {
* which is associated with the new history entry created by replaceState() * which is associated with the new history entry created by replaceState()
*/ */
function historyCleaner(details) { function historyCleaner(details) {
if(storage.globalStatus) { if (storage.globalStatus && storage.historyListenerEnabled) {
const urlBefore = details.url; const urlBefore = details.url;
const urlAfter = pureCleaning(details.url); const urlAfter = pureCleaning(details.url);
if (urlBefore !== urlAfter) { if (urlBefore !== urlAfter) {
browser.tabs.executeScript(details.tabId, { browser.scripting.executeScript({
frameId: details.frameId, target: {
code: 'history.replaceState({state: null},"",'+JSON.stringify(urlAfter)+');' tabId: details.tabId,
}).then(() => {}, onError); frameIds: [
details.frameId
]
},
func: (url) => history.replaceState({state: null}, "", url),
args: [
urlAfter
]
}).then(() => {
}, onError);
} }
} }
} }

View File

@@ -132,8 +132,7 @@ function getData() {
} }
}).catch(handleError); }).catch(handleError);
loadData("contextMenuEnabled") loadData("historyListenerEnabled")
.then(() => loadData("historyListenerEnabled"))
.then(() => loadData("localHostsSkipping")) .then(() => loadData("localHostsSkipping"))
.then(() => loadData("referralMarketing")) .then(() => loadData("referralMarketing"))
.then(() => loadData("domainBlocking")) .then(() => loadData("domainBlocking"))
@@ -142,7 +141,6 @@ function getData() {
.then(() => { .then(() => {
changeSwitchButton("localHostsSkipping", "localHostsSkipping"); changeSwitchButton("localHostsSkipping", "localHostsSkipping");
changeSwitchButton("historyListenerEnabled", "historyListenerEnabled"); changeSwitchButton("historyListenerEnabled", "historyListenerEnabled");
changeSwitchButton("contextMenuEnabled", "contextMenuEnabled");
changeSwitchButton("referralMarketing", "referralMarketing"); changeSwitchButton("referralMarketing", "referralMarketing");
changeSwitchButton("domainBlocking", "domainBlocking"); changeSwitchButton("domainBlocking", "domainBlocking");
changeSwitchButton("pingBlocking", "pingBlocking"); changeSwitchButton("pingBlocking", "pingBlocking");
@@ -219,7 +217,6 @@ function setText() {
document.getElementById('types_label').innerHTML = translate('setting_types_label'); document.getElementById('types_label').innerHTML = translate('setting_types_label');
document.getElementById('save_settings_btn').textContent = translate('settings_html_save_button'); document.getElementById('save_settings_btn').textContent = translate('settings_html_save_button');
document.getElementById('save_settings_btn').setAttribute('title', translate('settings_html_save_button_title')); document.getElementById('save_settings_btn').setAttribute('title', translate('settings_html_save_button_title'));
injectText("context_menu_enabled", "context_menu_enabled");
document.getElementById('history_listener_enabled').innerHTML = translate('history_listener_enabled'); document.getElementById('history_listener_enabled').innerHTML = translate('history_listener_enabled');
injectText("local_hosts_skipping", "local_hosts_skipping"); injectText("local_hosts_skipping", "local_hosts_skipping");
document.getElementById('export_settings_btn_text').textContent = translate('setting_html_export_button'); document.getElementById('export_settings_btn_text').textContent = translate('setting_html_export_button');

View File

@@ -86,7 +86,7 @@ function saveOnDisk(keys) {
} }
/** /**
* Schedule to save a key to disk in 30 seconds. * Schedule to save a key to disk in 60 seconds.
* @param {String} key * @param {String} key
*/ */
function deferSaveOnDisk(key) { function deferSaveOnDisk(key) {
@@ -95,13 +95,20 @@ function deferSaveOnDisk(key) {
return; return;
} }
setTimeout(function () { browser.alarms.create("deferSaveOnDisk", {
delayInMinutes: 1
});
hasPendingSaves = true;
}
browser.alarms.onAlarm.addListener(function (alarmInfo) {
if (alarmInfo.name === "deferSaveOnDisk") {
saveOnDisk(Array.from(pendingSaves)); saveOnDisk(Array.from(pendingSaves));
pendingSaves.clear(); pendingSaves.clear();
hasPendingSaves = false; hasPendingSaves = false;
}, 30000);
hasPendingSaves = true;
} }
});
/** /**
* Start sequence for ClearURLs. * Start sequence for ClearURLs.
@@ -115,12 +122,6 @@ function genesis() {
//Set correct icon on startup //Set correct icon on startup
changeIcon(); changeIcon();
// Start the context_menu
contextMenuStart();
// Start history listener
historyListenerStart();
}, handleError); }, handleError);
} }
@@ -216,7 +217,6 @@ function initSettings() {
storage.badged_color = "#ffa500"; storage.badged_color = "#ffa500";
storage.hashURL = "https://rules2.clearurls.xyz/rules.minify.hash"; storage.hashURL = "https://rules2.clearurls.xyz/rules.minify.hash";
storage.ruleURL = "https://rules2.clearurls.xyz/data.minify.json"; storage.ruleURL = "https://rules2.clearurls.xyz/data.minify.json";
storage.contextMenuEnabled = true;
storage.historyListenerEnabled = true; storage.historyListenerEnabled = true;
storage.localHostsSkipping = true; storage.localHostsSkipping = true;
storage.referralMarketing = false; storage.referralMarketing = false;

View File

@@ -181,9 +181,9 @@ function changeIcon() {
checkOSAndroid().then((res) => { checkOSAndroid().then((res) => {
if (!res) { if (!res) {
if (storage.globalStatus) { if (storage.globalStatus) {
browser.browserAction.setIcon({path: "img/clearurls_128x128.png"}).catch(handleError); browser.action.setIcon({path: "img/clearurls_128x128.png"}).catch(handleError);
} else { } else {
browser.browserAction.setIcon({path: "img/clearurls_gray_128x128.png"}).catch(handleError); browser.action.setIcon({path: "img/clearurls_gray_128x128.png"}).catch(handleError);
} }
} }
}); });
@@ -200,13 +200,13 @@ function setBadgedStatus() {
let color = storage.badged_color; let color = storage.badged_color;
if (storage.badged_color.charAt(0) !== '#') if (storage.badged_color.charAt(0) !== '#')
color = '#' + storage.badged_color; color = '#' + storage.badged_color;
browser.browserAction.setBadgeBackgroundColor({ browser.action.setBadgeBackgroundColor({
'color': color 'color': color
}).catch(handleError); }).catch(handleError);
// Works only in Firefox: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/browserAction/setBadgeTextColor#Browser_compatibility // Works only in Firefox: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/action/setBadgeTextColor#Browser_compatibility
if (getBrowser() === "Firefox") { if (getBrowser() === "Firefox") {
browser.browserAction.setBadgeTextColor({ browser.action.setBadgeTextColor({
color: "#FFFFFF" color: "#FFFFFF"
}).catch(handleError); }).catch(handleError);
} }

View File

@@ -24,12 +24,15 @@
* *
* This watchdog restarts the whole Add-on, when the check fails. * This watchdog restarts the whole Add-on, when the check fails.
*/ */
const CHECK_INTERVAL = 60000;
const __dirtyURL = "https://clearurls.roebert.eu?utm_source=addon"; const __dirtyURL = "https://clearurls.roebert.eu?utm_source=addon";
const __cleanURL = new URL("https://clearurls.roebert.eu").toString(); const __cleanURL = new URL("https://clearurls.roebert.eu").toString();
setInterval(function() { browser.alarms.create("watchdog", {
if(isStorageAvailable() && storage.globalStatus) { periodInMinutes: 1,
});
browser.alarms.onAlarm.addListener(function (alarmInfo) {
if (alarmInfo.name === "watchdog" && isStorageAvailable() && storage.globalStatus) {
if (new URL(pureCleaning(__dirtyURL, true)).toString() !== __cleanURL) { if (new URL(pureCleaning(__dirtyURL, true)).toString() !== __cleanURL) {
storage.watchDogErrorCount += 1; storage.watchDogErrorCount += 1;
console.log(translate('watchdog', storage.watchDogErrorCount)); console.log(translate('watchdog', storage.watchDogErrorCount));
@@ -40,4 +43,4 @@ setInterval(function() {
saveOnExit(); saveOnExit();
} }
} }
}, CHECK_INTERVAL); });

View File

@@ -1,16 +0,0 @@
/*
* Source: https://github.com/mdn/webextensions-examples/tree/master/context-menu-copy-link-with-types
*/
function copyToClipboard(text) {
function oncopy(event) {
document.removeEventListener("copy", oncopy, true);
event.stopImmediatePropagation();
event.preventDefault();
event.clipboardData.setData("text/plain", text);
}
document.addEventListener("copy", oncopy, true);
document.execCommand("copy");
}

View File

@@ -136,13 +136,6 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
<span class="slider round"></span> <span class="slider round"></span>
</label> </label>
</p> </p>
<p>
<label id="context_menu_enabled" style="font-weight: bold;"></label><br />
<label class="switch">
<input type="checkbox" id="contextMenuEnabled">
<span class="slider round"></span>
</label>
</p>
<p> <p>
<label id="referral_marketing_enabled" style="font-weight: bold;"></label><br /> <label id="referral_marketing_enabled" style="font-weight: bold;"></label><br />
<label class="switch"> <label class="switch">

View File

@@ -1,12 +1,14 @@
{ {
"manifest_version": 2, "manifest_version": 3,
"name": "ClearURLs", "name": "ClearURLs",
"version": "1.27.0", "version": "1.28.0",
"author": "Kevin Roebert", "author": "Kevin Roebert",
"description": "__MSG_extension_description__", "description": "__MSG_extension_description__",
"homepage_url": "https://docs.clearurls.xyz", "homepage_url": "https://docs.clearurls.xyz",
"default_locale": "en", "default_locale": "en",
"content_security_policy": "script-src 'self'; object-src 'none'", "content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'none'"
},
"browser_specific_settings": { "browser_specific_settings": {
"gecko": { "gecko": {
"id": "{74145f27-f039-47ce-a470-a662b129930a}" "id": "{74145f27-f039-47ce-a470-a662b129930a}"
@@ -25,8 +27,7 @@
"96": "img/clearurls_96x96.png", "96": "img/clearurls_96x96.png",
"128": "img/clearurls_128x128.png" "128": "img/clearurls_128x128.png"
}, },
"browser_action": { "action": {
"browser_style": true,
"default_icon": { "default_icon": {
"16": "img/clearurls_16x16.png", "16": "img/clearurls_16x16.png",
"19": "img/clearurls_19x19.png", "19": "img/clearurls_19x19.png",
@@ -44,7 +45,6 @@
"default_popup": "html/popup.html" "default_popup": "html/popup.html"
}, },
"permissions": [ "permissions": [
"<all_urls>",
"webRequest", "webRequest",
"webRequestBlocking", "webRequestBlocking",
"storage", "storage",
@@ -52,7 +52,12 @@
"contextMenus", "contextMenus",
"webNavigation", "webNavigation",
"tabs", "tabs",
"downloads" "downloads",
"scripting",
"alarms"
],
"host_permissions": [
"<all_urls>"
], ],
"background": { "background": {
"scripts": [ "scripts": [