Migrating Firefox manifest to v3 / Moving common functions into separate files

pull/433/head
Kevin Payravi 2024-01-10 03:21:47 -06:00
parent 66f4bf7a7f
commit cd6e924908
11 changed files with 781 additions and 1239 deletions

View File

@ -1,3 +1,7 @@
if (typeof importScripts !== 'undefined') {
importScripts('common-functions-general.js');
}
// Capture web requests
chrome.webRequest.onBeforeSendHeaders.addListener(
async (event) => {
@ -48,67 +52,7 @@ chrome.runtime.onInstalled.addListener(async (detail) => {
// Temporary functions for 3.0 migration
if (detail.reason === 'update') {
await chrome.storage.sync.get(async (storage) => {
if (!storage.v3migration) {
let defaultWikiAction = storage.defaultWikiAction || 'alert';
let defaultSearchAction = storage.defaultSearchAction || 'replace';
// Set new default action settings:
if (!storage.defaultWikiAction) {
if (storage.defaultActionSettings && storage.defaultActionSettings['EN']) {
defaultWikiAction = storage.defaultActionSettings['EN'];
}
chrome.storage.sync.set({ 'defaultWikiAction': defaultWikiAction });
}
if (!storage.defaultSearchAction) {
if (storage.defaultSearchFilterSettings && storage.defaultSearchFilterSettings['EN']) {
if (storage.defaultSearchFilterSettings['EN'] === 'false') {
defaultSearchAction = 'disabled';
} else {
defaultSearchAction = 'replace';
}
}
chrome.storage.sync.set({ 'defaultSearchAction': defaultSearchAction });
}
// Remove old objects:
chrome.storage.sync.remove('defaultActionSettings');
chrome.storage.sync.remove('defaultSearchFilterSettings');
// Migrate wiki settings to new searchEngineSettings and wikiSettings objects
sites = await getData();
let siteSettings = storage.siteSettings || {};
let searchEngineSettings = storage.searchEngineSettings || {};
let wikiSettings = storage.wikiSettings || {};
sites.forEach((site) => {
if (!searchEngineSettings[site.id]) {
if (siteSettings[site.id] && siteSettings[site.id].searchFilter) {
if (siteSettings[site.id].searchFilter === 'false') {
searchEngineSettings[site.id] = 'disabled';
} else {
searchEngineSettings[site.id] = 'replace';
}
} else {
searchEngineSettings[site.id] = defaultSearchAction;
}
}
if (!wikiSettings[site.id]) {
wikiSettings[site.id] = siteSettings[site.id]?.action || defaultWikiAction;
}
});
chrome.storage.sync.set({ 'searchEngineSettings': searchEngineSettings });
chrome.storage.sync.set({ 'wikiSettings': wikiSettings });
// Remove old object:
chrome.storage.sync.remove('siteSettings');
// Mark v3 migration as complete:
chrome.storage.sync.set({ 'v3migration': 'done' });
}
});
commonFunctionMigrateToV3();
}
});
@ -204,40 +148,6 @@ function redirectToBreezeWiki(storage, tabId, url) {
}
}
// Load website data
async function getData() {
const LANGS = ["DE", "EN", "ES", "FR", "IT", "KO", "PL", "PT", "RU", "TOK", "UK", "ZH"];
let sites = [];
let promises = [];
for (let i = 0; i < LANGS.length; i++) {
promises.push(fetch(chrome.runtime.getURL('data/sites' + LANGS[i] + '.json'))
.then((resp) => resp.json())
.then((jsonData) => {
jsonData.forEach((site) => {
site.origins.forEach((origin) => {
sites.push({
"id": site.id,
"origin": origin.origin,
"origin_base_url": origin.origin_base_url,
"origin_content_path": origin.origin_content_path,
"origin_main_page": origin.origin_main_page,
"destination": site.destination,
"destination_base_url": site.destination_base_url,
"destination_search_path": site.destination_search_path,
"destination_content_prefix": origin.destination_content_prefix || site.destination_content_prefix || "",
"destination_platform": site.destination_platform,
"destination_icon": site.destination_icon,
"destination_main_page": site.destination_main_page,
"lang": LANGS[i]
})
})
});
}));
}
await Promise.all(promises);
return sites;
}
async function main(url, tabId) {
// Create object prototypes for getting and setting attributes
Object.prototype.get = function (prop) {
@ -252,113 +162,95 @@ async function main(url, tabId) {
// This is mainly to prevent background processes from triggering an event
let sites = [];
sites = await getData();
chrome.storage.local.get((localStorage) => {
chrome.storage.sync.get((syncStorage) => {
chrome.storage.sync.get(async (syncStorage) => {
const storage = { ...syncStorage, ...localStorage };
if ((storage.power ?? 'on') === 'on') {
let crossLanguageSetting = storage.crossLanguage || 'off';
// Check if site is in our list of wikis:
let matchingSites = [];
if (crossLanguageSetting === 'on') {
matchingSites = sites.filter(el => url.replace(/^https?:\/\//, '').startsWith(el.origin_base_url));
} else {
matchingSites = sites.filter(el => url.replace(/^https?:\/\//, '').startsWith(el.origin_base_url + el.origin_content_path));
}
if (matchingSites.length > 0) {
// Select match with longest base URL
let closestMatch = "";
matchingSites.forEach(site => {
if (site.origin_base_url.length > closestMatch.length) {
closestMatch = site.origin_base_url;
}
});
let site = matchingSites.find(site => site.origin_base_url === closestMatch);
if (site) {
// Get user's settings for the wiki
let settings = storage.wikiSettings || {};
let id = site['id'];
let siteSetting = settings[id] || storage.defaultWikiAction || 'alert';
let matchingSite = await commonFunctionFindMatchingSite(url, crossLanguageSetting);
if (matchingSite) {
// Get user's settings for the wiki
let settings = storage.wikiSettings || {};
let id = matchingSite['id'];
let siteSetting = settings[id] || storage.defaultWikiAction || 'alert';
// Remove query paramters
let urlObj = new URL(url);
urlObj.search = '';
url = String(decodeURIComponent(urlObj.toString()));
// Remove query paramters
let urlObj = new URL(url);
urlObj.search = '';
url = String(decodeURIComponent(urlObj.toString()));
// Check if redirects are enabled for the site
if (siteSetting === 'redirect') {
// Get article name from the end of the URL;
// We can't just take the last part of the path due to subpages;
// Instead, we take everything after the wiki's base URL + content path
let originArticle = decodeURIComponent(url.split(site['origin_base_url'] + site['origin_content_path'])[1] || '');
let destinationArticle = site['destination_content_prefix'] + originArticle;
// Set up URL to redirect user to based on wiki platform
let newURL = '';
if (originArticle) {
// Check if main page
if (originArticle === site['origin_main_page']) {
switch (site['destination_platform']) {
case 'doku':
destinationArticle = '';
break;
default:
destinationArticle = site['destination_main_page'];
}
}
// Replace underscores with spaces as that performs better in search
destinationArticle = destinationArticle.replaceAll('_', ' ');
// If a Fextralife wiki, replace plus signs with spaces
// When there are multiple plus signs together, this regex will only replace only the first
if (site['origin_base_url'].includes('.wiki.fextralife.com')) {
destinationArticle = destinationArticle.replace(/(?<!\+)\+/g, ' ');
}
// Encode article
destinationArticle = encodeURIComponent(destinationArticle);
let searchParams = '';
switch (site['destination_platform']) {
case 'mediawiki':
searchParams = '?search=' + destinationArticle;
break;
// Check if redirects are enabled for the site
if (siteSetting === 'redirect') {
// Get article name from the end of the URL;
// We can't just take the last part of the path due to subpages;
// Instead, we take everything after the wiki's base URL + content path
let originArticle = decodeURIComponent(url.split(matchingSite['origin_base_url'] + matchingSite['origin_content_path'])[1] || '');
let destinationArticle = matchingSite['destination_content_prefix'] + originArticle;
// Set up URL to redirect user to based on wiki platform
let newURL = '';
if (originArticle) {
// Check if main page
if (originArticle === matchingSite['origin_main_page']) {
switch (matchingSite['destination_platform']) {
case 'doku':
searchParams = 'start?do=search&q=' + destinationArticle;
destinationArticle = '';
break;
default:
destinationArticle = matchingSite['destination_main_page'];
}
newURL = 'https://' + site["destination_base_url"] + site["destination_search_path"] + searchParams;
} else {
newURL = 'https://' + site["destination_base_url"];
}
// Perform redirect
chrome.tabs.update(tabId, { url: newURL });
// Replace underscores with spaces as that performs better in search
destinationArticle = destinationArticle.replaceAll('_', ' ');
// Increase redirect count
chrome.storage.sync.set({ 'countRedirects': (storage.countRedirects ?? 0) + 1 });
// Notify if enabled
if ((storage.notifications ?? 'on') === 'on') {
// Notify that user is being redirected
let notifID = 'independent-wiki-redirector-notification-' + Math.floor(Math.random() * 1E16);
chrome.notifications.create(notifID, {
"type": "basic",
"iconUrl": 'images/logo-48.png',
"title": "You've been redirected!",
"message": "Indie Wiki Buddy has sent you from " + site['origin'] + " to " + site['destination']
});
// Self-clear notification after 6 seconds
setTimeout(() => { chrome.notifications.clear(notifID); }, 6000);
// If a Fextralife wiki, replace plus signs with spaces
// When there are multiple plus signs together, this regex will only replace only the first
if (matchingSite['origin_base_url'].includes('.wiki.fextralife.com')) {
destinationArticle = destinationArticle.replace(/(?<!\+)\+/g, ' ');
}
} else if ((storage.breezewiki ?? 'off') === 'on' || (storage.breezewiki ?? 'off') === 'redirect') {
redirectToBreezeWiki(storage, tabId, url);
// Encode article
destinationArticle = encodeURIComponent(destinationArticle);
let searchParams = '';
switch (matchingSite['destination_platform']) {
case 'mediawiki':
searchParams = '?search=' + destinationArticle;
break;
case 'doku':
searchParams = 'start?do=search&q=' + destinationArticle;
break;
}
newURL = 'https://' + matchingSite["destination_base_url"] + matchingSite["destination_search_path"] + searchParams;
} else {
newURL = 'https://' + matchingSite["destination_base_url"];
}
// Perform redirect
chrome.tabs.update(tabId, { url: newURL });
// Increase redirect count
chrome.storage.sync.set({ 'countRedirects': (storage.countRedirects ?? 0) + 1 });
// Notify if enabled
if ((storage.notifications ?? 'on') === 'on') {
// Notify that user is being redirected
let notifID = 'independent-wiki-redirector-notification-' + Math.floor(Math.random() * 1E16);
chrome.notifications.create(notifID, {
"type": "basic",
"iconUrl": 'images/logo-48.png',
"title": "You've been redirected!",
"message": "Indie Wiki Buddy has sent you from " + matchingSite['origin'] + " to " + matchingSite['destination']
});
// Self-clear notification after 6 seconds
setTimeout(() => { chrome.notifications.clear(notifID); }, 6000);
}
} else if ((storage.breezewiki ?? 'off') === 'on' || (storage.breezewiki ?? 'off') === 'redirect') {
redirectToBreezeWiki(storage, tabId, url);
}
} else if ((storage.breezewiki ?? 'off') === 'on' || (storage.breezewiki ?? 'off') === 'redirect') {
redirectToBreezeWiki(storage, tabId, url);
}
} else if ((storage.breezewiki ?? 'off') === 'on' || (storage.breezewiki ?? 'off') === 'redirect') {
redirectToBreezeWiki(storage, tabId, url);
}
});
});

142
common-functions-general.js Normal file
View File

@ -0,0 +1,142 @@
// Load wiki data objects, with each destination having its own object
async function commonFunctionGetSiteDataByDestination() {
const LANGS = ["DE", "EN", "ES", "FR", "IT", "KO", "PL", "PT", "RU", "TOK", "UK", "ZH"];
var sites = [];
let promises = [];
for (let i = 0; i < LANGS.length; i++) {
promises.push(fetch(chrome.runtime.getURL('data/sites' + LANGS[i] + '.json'))
.then((resp) => resp.json())
.then((jsonData) => {
jsonData.forEach((site) => site.language = LANGS[i]);
sites = sites.concat(jsonData);
}));
}
await Promise.all(promises);
return sites;
}
// Load wiki data objects, with each origin having its own object
async function commonFunctionGetSiteDataByOrigin() {
const LANGS = ["DE", "EN", "ES", "FR", "IT", "KO", "PL", "PT", "RU", "TOK", "UK", "ZH"];
let sites = [];
let promises = [];
for (let i = 0; i < LANGS.length; i++) {
promises.push(fetch(chrome.runtime.getURL('data/sites' + LANGS[i] + '.json'))
.then((resp) => resp.json())
.then((jsonData) => {
jsonData.forEach((site) => {
site.origins.forEach((origin) => {
sites.push({
"id": site.id,
"origin": origin.origin,
"origin_base_url": origin.origin_base_url,
"origin_content_path": origin.origin_content_path,
"origin_main_page": origin.origin_main_page,
"destination": site.destination,
"destination_base_url": site.destination_base_url,
"destination_search_path": site.destination_search_path,
"destination_content_prefix": origin.destination_content_prefix || site.destination_content_prefix || "",
"destination_platform": site.destination_platform,
"destination_icon": site.destination_icon,
"destination_main_page": site.destination_main_page,
"tags": site.tags || [],
"language": LANGS[i]
})
})
});
}));
}
await Promise.all(promises);
return sites;
}
// Given a URL, find closest match in our dataset
async function commonFunctionFindMatchingSite(site, crossLanguageSetting) {
let matchingSite = commonFunctionGetSiteDataByOrigin().then(sites => {
let matchingSites = [];
if (crossLanguageSetting === 'on') {
matchingSites = sites.filter(el => site.replace(/^https?:\/\//, '').startsWith(el.origin_base_url));
} else {
matchingSites = sites.filter(el => site.replace(/^https?:\/\//, '').startsWith(el.origin_base_url + el.origin_content_path));
}
if (matchingSites.length > 0) {
// Select match with longest base URL
let closestMatch = '';
matchingSites.forEach(site => {
if (site.origin_base_url.length > closestMatch.length) {
closestMatch = site.origin_base_url;
}
});
return matchingSites.find(site => site.origin_base_url === closestMatch);
} else {
return null;
}
});
return matchingSite;
}
// Temporary function to migrate user data to IWB version 3.0+
async function commonFunctionMigrateToV3() {
await chrome.storage.sync.get(async (storage) => {
if (!storage.v3migration) {
let defaultWikiAction = storage.defaultWikiAction || 'alert';
let defaultSearchAction = storage.defaultSearchAction || 'replace';
// Set new default action settings:
if (!storage.defaultWikiAction) {
if (storage.defaultActionSettings && storage.defaultActionSettings['EN']) {
defaultWikiAction = storage.defaultActionSettings['EN'];
}
chrome.storage.sync.set({ 'defaultWikiAction': defaultWikiAction });
}
if (!storage.defaultSearchAction) {
if (storage.defaultSearchFilterSettings && storage.defaultSearchFilterSettings['EN']) {
if (storage.defaultSearchFilterSettings['EN'] === 'false') {
defaultSearchAction = 'disabled';
} else {
defaultSearchAction = 'replace';
}
}
chrome.storage.sync.set({ 'defaultSearchAction': defaultSearchAction });
}
// Remove old objects:
chrome.storage.sync.remove('defaultActionSettings');
chrome.storage.sync.remove('defaultSearchFilterSettings');
// Migrate wiki settings to new searchEngineSettings and wikiSettings objects
sites = await commonFunctionGetSiteDataByOrigin();
let siteSettings = storage.siteSettings || {};
let searchEngineSettings = storage.searchEngineSettings || {};
let wikiSettings = storage.wikiSettings || {};
sites.forEach((site) => {
if (!searchEngineSettings[site.id]) {
if (siteSettings[site.id] && siteSettings[site.id].searchFilter) {
if (siteSettings[site.id].searchFilter === 'false') {
searchEngineSettings[site.id] = 'disabled';
} else {
searchEngineSettings[site.id] = 'replace';
}
} else {
searchEngineSettings[site.id] = defaultSearchAction;
}
}
if (!wikiSettings[site.id]) {
wikiSettings[site.id] = siteSettings[site.id]?.action || defaultWikiAction;
}
});
chrome.storage.sync.set({ 'searchEngineSettings': searchEngineSettings });
chrome.storage.sync.set({ 'wikiSettings': wikiSettings });
// Remove old object:
chrome.storage.sync.remove('siteSettings');
// Mark v3 migration as complete:
chrome.storage.sync.set({ 'v3migration': 'done' });
}
});
}

View File

@ -0,0 +1,322 @@
// Set setting toggle values on-load:
chrome.storage.local.get({ 'power': 'on' }, (item) => {
setPower(item.power, false);
});
chrome.storage.sync.get({ 'notifications': 'on' }, (item) => {
setNotifications(item.notifications, false);
});
chrome.storage.sync.get({ 'hiddenResultsBanner': 'on' }, (item) => {
setHiddenResultsBanner(item.hiddenResultsBanner, false);
});
chrome.storage.sync.get({ 'crossLanguage': 'off' }, (item) => {
setCrossLanguage(item.crossLanguage, false);
});
chrome.storage.sync.get({ 'openChangelog': 'off' }, (item) => {
setOpenChangelog(item.openChangelog, false);
});
chrome.storage.sync.get({ 'breezewiki': 'off' }, (item) => {
// Account for legacy 'on' setting for BreezeWiki
if (item.breezewiki === 'on') {
setBreezeWiki('redirect');
} else {
setBreezeWiki(item.breezewiki, false);
}
// Load BreezeWiki options if BreezeWiki is enabled
if (item.breezewiki !== 'off') {
loadBreezewikiOptions();
}
});
// Add event listener for power toggle
document.getElementById('powerCheckbox').addEventListener('change', () => {
chrome.storage.local.get({ 'power': 'on' }, (item) => {
if (item.power === 'on') {
setPower('off');
} else {
setPower('on');
}
});
});
// Set notifications setting
function setNotifications(setting, storeSetting = true) {
if (storeSetting) {
chrome.storage.sync.set({ 'notifications': setting });
}
const notificationsIcon = document.getElementById('notificationsIcon');
if (setting === 'on') {
document.getElementById('notificationsCheckbox').checked = true;
notificationsIcon.innerText = '🔔';
} else {
document.getElementById('notificationsCheckbox').checked = false;
notificationsIcon.innerText = '🔕';
}
}
// Set search results hidden banner setting
function setHiddenResultsBanner(setting, storeSetting = true) {
if (storeSetting) {
chrome.storage.sync.set({ 'hiddenResultsBanner': setting });
}
const hiddenResultsBannerIcon = document.getElementById('hiddenResultsBannerIcon');
if (setting === 'on') {
document.getElementById('hiddenResultsBannerCheckbox').checked = true;
hiddenResultsBannerIcon.innerText = '🔔';
} else {
document.getElementById('hiddenResultsBannerCheckbox').checked = false;
hiddenResultsBannerIcon.innerText = '🔕';
}
}
// Set cross-language setting
function setCrossLanguage(setting, storeSetting = true) {
if (storeSetting) {
chrome.storage.sync.set({ 'crossLanguage': setting });
}
const crossLanguageIcon = document.getElementById('crossLanguageIcon');
if (setting === 'on') {
document.getElementById('crossLanguageCheckbox').checked = true;
crossLanguageIcon.innerText = '🌐';
} else {
document.getElementById('crossLanguageCheckbox').checked = false;
crossLanguageIcon.innerText = '⚪️';
}
}
// Set open changelog setting
function setOpenChangelog(setting, storeSetting = true) {
if (storeSetting) {
chrome.storage.sync.set({ 'openChangelog': setting });
}
const openChangelogIcon = document.getElementById('openChangelogIcon');
if (setting === 'on') {
document.getElementById('openChangelogCheckbox').checked = true;
openChangelogIcon.innerText = '📂';
} else {
document.getElementById('openChangelogCheckbox').checked = false;
openChangelogIcon.innerText = '📁';
}
}
// Event listeners for general setting toggles
document.getElementById('notificationsCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'notifications': 'on' }, (item) => {
if (item.notifications === 'on') {
setNotifications('off');
} else {
setNotifications('on');
}
});
});
document.getElementById('hiddenResultsBannerCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'hiddenResultsBanner': 'on' }, (item) => {
if (item.hiddenResultsBanner === 'on') {
setHiddenResultsBanner('off');
} else {
setHiddenResultsBanner('on');
}
});
});
document.getElementById('crossLanguageCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'crossLanguage': 'off' }, (item) => {
if (item.crossLanguage === 'on') {
setCrossLanguage('off');
} else {
setCrossLanguage('on');
}
});
});
document.getElementById('openChangelogCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'openChangelog': 'off' }, (item) => {
if (item.openChangelog === 'on') {
setOpenChangelog('off');
} else {
setOpenChangelog('on');
}
});
});
document.querySelectorAll('[name="breezewikiSetting"]').forEach((el) => {
el.addEventListener('change', async () => {
const settingValue = document.options.breezewikiSetting.value;
chrome.storage.sync.set({ 'breezewiki': settingValue });
setBreezeWiki(settingValue);
if (settingValue !== 'off') {
loadBreezewikiOptions();
}
});
});
// Set BreezeWiki settings
function setBreezeWiki(setting, storeSetting = true) {
// Account for legacy BreezeWiki sestting ('on' is now 'redirect')
if (setting === 'on') {
setting = 'redirect';
}
// Store BreezeWiki setting
if (storeSetting) {
chrome.storage.sync.set({ 'breezewiki': setting });
}
// Set BreezeWiki value on radio group
document.options.breezewikiSetting.value = setting;
// Toggle/update host display
const breezewikiHost = document.getElementById('breezewikiHost');
if (setting !== 'off') {
breezewikiHost.style.display = 'block';
chrome.storage.sync.get({ 'breezewikiHost': null }, (host) => {
if (!host.breezewikiHost) {
fetch('https://bw.getindie.wiki/instances.json')
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Indie Wiki Buddy failed to get BreezeWiki data.');
}).then((breezewikiHosts) => {
breezewikiHosts = breezewikiHosts.filter(host =>
chrome.runtime.getManifest().version.localeCompare(host.iwb_version,
undefined,
{ numeric: true, sensitivity: 'base' }
) >= 0
);
// Check if BreezeWiki's main site is available
let breezewikiMain = breezewikiHosts.filter(host => host.instance === 'https://breezewiki.com');
if (breezewikiMain.length > 0) {
host.breezewikiHost = breezewikiMain[0].instance;
} else {
// If BreezeWiki.com is not available, set to a random mirror
try {
host.breezewikiHost = breezewikiHosts[Math.floor(Math.random() * breezewikiHosts.length)].instance;
} catch (e) {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
}
}
chrome.storage.sync.set({ 'breezewikiHost': host.breezewikiHost });
chrome.storage.sync.set({ 'breezewikiHostOptions': breezewikiHosts });
chrome.storage.sync.set({ 'breezewikiHostFetchTimestamp': Date.now() });
document.getElementById('breezewikiHostSelect').value = host.breezewikiHost;
}).catch((e) => {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
// If fetch fails and no host is set, default to breezewiki.com:
if (!host) {
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com' });
}
});
} else {
document.getElementById('breezewikiHostSelect').value = host.breezewikiHost;
}
});
} else {
breezewikiHost.style.display = 'none';
}
}
function populateBreezewikiHosts(breezewikiHosts, selectedHost, customHostName) {
// Populate dropdown selection of hosts
const breezewikiHostSelect = document.getElementById('breezewikiHostSelect');
while (breezewikiHostSelect.firstChild) {
// Remove any existing options
breezewikiHostSelect.removeChild(breezewikiHostSelect.firstChild);
}
// Add known BreezeWiki domains:
for (var i = 0; i < breezewikiHosts.length; i++) {
let option = document.createElement('option');
option.value = breezewikiHosts[i].instance;
let textContent = breezewikiHosts[i].instance.replace('https://', '');
const numberOfPeriods = (textContent.match(/\./g) || []).length;
if (numberOfPeriods > 1) {
textContent = textContent.substring(textContent.indexOf('.') + 1);
}
option.textContent = textContent;
breezewikiHostSelect.appendChild(option);
}
// Add custom BreezeWiki host option:
let customOption = document.createElement('option');
customOption.value = 'CUSTOM';
customOption.textContent = 'Custom host...';
breezewikiHostSelect.appendChild(customOption);
breezewikiHostSelect.value = selectedHost;
// Set up custom domain input:
if (breezewikiHostSelect.value === 'CUSTOM') {
document.getElementById('breezewikiCustomHost').style.display = 'block';
} else {
document.getElementById('breezewikiCustomHost').style.display = 'none';
}
document.getElementById('customBreezewikiHost').value = customHostName.replace(/^https?:\/\//i, '');
}
// Populate BreezeWiki dropdown when enabled
async function loadBreezewikiOptions() {
// Load BreezeWiki options:
chrome.storage.sync.get(['breezewikiHostOptions', 'breezewikiHostFetchTimestamp', 'breezewikiHost', 'breezewikiCustomHost'], (item) => {
let hostOptions = item.breezewikiHostOptions;
let hostFetchTimestamp = item.breezewikiHostFetchTimestamp;
let host = item.breezewikiHost;
let customHost = item.breezewikiCustomHost || '';
// Fetch and cache list of BreezeWiki hosts if first time,
// or if it has been 24 hrs since last refresh
if (!host || !hostOptions || !hostFetchTimestamp || (Date.now() - 86400000 > hostFetchTimestamp)) {
fetch('https://bw.getindie.wiki/instances.json')
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Indie Wiki Buddy failed to get BreezeWiki data.');
}).then((breezewikiHosts) => {
breezewikiHosts = breezewikiHosts.filter(host =>
chrome.runtime.getManifest().version.localeCompare(host.iwb_version,
undefined,
{ numeric: true, sensitivity: 'base' }
) >= 0
);
// If host isn't set, or currently selected host is no longer available, select random host:
if (!host || !breezewikiHosts.some(item => item.instance === host)) {
// Check if BreezeWiki's main site is available
let breezewikiMain = breezewikiHosts.filter(host => host.instance === 'https://breezewiki.com');
if (breezewikiMain.length > 0) {
host = breezewikiMain[0].instance;
} else {
// If BreezeWiki.com is not available, set to a random mirror
try {
host = breezewikiHosts[Math.floor(Math.random() * breezewikiHosts.length)].instance;
} catch (e) {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
}
}
}
populateBreezewikiHosts(breezewikiHosts, host, customHost);
// Store BreezeWiki host details
chrome.storage.sync.set({ 'breezewikiHost': host });
chrome.storage.sync.set({ 'breezewikiHostOptions': breezewikiHosts });
chrome.storage.sync.set({ 'breezewikiHostFetchTimestamp': Date.now() });
}).catch((e) => {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
// If fetch fails and no host is set, default to breezewiki.com:
if (!host) {
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com' });
}
});
} else {
// If currently selected host is no longer available, select random host:
if (host !== 'CUSTOM' && !hostOptions.some(item => item.instance === host)) {
host = hostOptions[Math.floor(Math.random() * hostOptions.length)].instance;
}
populateBreezewikiHosts(hostOptions, host, customHost);
// Store BreezeWiki host details
chrome.storage.sync.set({ 'breezewikiHost': host });
}
});
}

View File

@ -11,40 +11,6 @@ Object.prototype.set = function (prop, value) {
this[prop] = value;
}
// Load website data:
async function getData() {
let sites = [];
let promises = [];
for (let i = 0; i < LANGS.length; i++) {
promises.push(fetch(chrome.runtime.getURL('data/sites' + LANGS[i] + '.json'))
.then((resp) => resp.json())
.then((jsonData) => {
jsonData.forEach((site) => {
site.origins.forEach((origin) => {
sites.push({
"id": site.id,
"origin": origin.origin,
"origin_base_url": origin.origin_base_url,
"origin_content_path": origin.origin_content_path,
"origin_main_page": origin.origin_main_page,
"destination": site.destination,
"destination_base_url": site.destination_base_url,
"destination_search_path": site.destination_search_path,
"destination_content_prefix": origin.destination_content_prefix || site.destination_content_prefix || "",
"destination_platform": site.destination_platform,
"destination_icon": site.destination_icon,
"destination_main_page": site.destination_main_page,
"lang": LANGS[i],
"tags": site.tags || []
})
})
});
}));
}
await Promise.all(promises);
return sites;
}
function outputCSS() {
if (!document.getElementById('iwb-banner-styles')) {
styleString = `
@ -382,96 +348,80 @@ function main() {
urlObj.search = '';
origin = String(decodeURIComponent(urlObj.toString()));
getData().then(sites => {
commonFunctionGetSiteDataByOrigin().then(async sites => {
let crossLanguageSetting = storage.crossLanguage || 'off';
// Check if site is in our list of wikis:
let matchingSites = [];
if (crossLanguageSetting === 'on') {
matchingSites = sites.filter(el => origin.replace(/^https?:\/\//, '').startsWith(el.origin_base_url));
} else {
matchingSites = sites.filter(el => origin.replace(/^https?:\/\//, '').startsWith(el.origin_base_url + el.origin_content_path));
}
if (matchingSites.length > 0) {
// Select match with longest base URL
let closestMatch = '';
matchingSites.forEach(site => {
if (site.origin_base_url.length > closestMatch.length) {
closestMatch = site.origin_base_url;
}
});
let site = matchingSites.find(site => site.origin_base_url === closestMatch);
if (site) {
// Get user's settings for the wiki
let id = site['id'];
let siteSetting = 'alert';
if (storage.wikiSettings && storage.wikiSettings[id]) {
siteSetting = storage.wikiSettings[id];
} else if (storage.defaultWikiAction) {
siteSetting = storage.defaultWikiAction;
}
let matchingSite = await commonFunctionFindMatchingSite(origin, crossLanguageSetting);
if (matchingSite) {
// Get user's settings for the wiki
let id = matchingSite['id'];
let siteSetting = 'alert';
if (storage.wikiSettings && storage.wikiSettings[id]) {
siteSetting = storage.wikiSettings[id];
} else if (storage.defaultWikiAction) {
siteSetting = storage.defaultWikiAction;
}
// Notify if enabled for the wiki:
if (siteSetting === 'alert') {
// Get article name from the end of the URL;
// We can't just take the last part of the path due to subpages;
// Instead, we take everything after the wiki's base URL + content path:
let originArticle = decodeURIComponent(origin.split(site['origin_base_url'] + site['origin_content_path'])[1] || '');
let destinationArticle = site['destination_content_prefix'] + originArticle;
// Set up URL to redirect user to based on wiki platform:
let newURL = '';
if (originArticle) {
// Check if main page
if (originArticle === site['origin_main_page']) {
switch (site['destination_platform']) {
case 'doku':
destinationArticle = '';
break;
default:
destinationArticle = site['destination_main_page'];
}
}
// Replace underscores with spaces as that performs better in search
destinationArticle = destinationArticle.replaceAll('_', ' ');
// If a Fextralife wiki, replace plus signs with spaces
// When there are multiple plus signs together, this regex will only replace only the first
if (site['origin_base_url'].includes('.wiki.fextralife.com')) {
destinationArticle = destinationArticle.replace(/(?<!\+)\+/g, ' ');
}
// Encode article
destinationArticle = encodeURIComponent(destinationArticle);
let searchParams = '';
switch (site['destination_platform']) {
case 'mediawiki':
searchParams = '?search=' + destinationArticle;
break;
// Notify if enabled for the wiki:
if (siteSetting === 'alert') {
// Get article name from the end of the URL;
// We can't just take the last part of the path due to subpages;
// Instead, we take everything after the wiki's base URL + content path:
let originArticle = decodeURIComponent(origin.split(matchingSite['origin_base_url'] + matchingSite['origin_content_path'])[1] || '');
let destinationArticle = matchingSite['destination_content_prefix'] + originArticle;
// Set up URL to redirect user to based on wiki platform:
let newURL = '';
if (originArticle) {
// Check if main page
if (originArticle === matchingSite['origin_main_page']) {
switch (matchingSite['destination_platform']) {
case 'doku':
searchParams = 'start?do=search&q=' + destinationArticle;
destinationArticle = '';
break;
default:
destinationArticle = matchingSite['destination_main_page'];
}
newURL = 'https://' + site["destination_base_url"] + site["destination_search_path"] + searchParams;
} else {
newURL = 'https://' + site["destination_base_url"];
}
// When head elem is loaded, notify that another wiki is available
const docObserver = new MutationObserver((mutations, mutationInstance) => {
const headElement = document.querySelector('head');
if (headElement) {
try {
displayRedirectBanner(newURL, site['id'], site['destination'], site['lang'], site['tags'], storage);
} finally {
mutationInstance.disconnect();
}
}
});
docObserver.observe(document, {
childList: true,
subtree: true
});
// Replace underscores with spaces as that performs better in search
destinationArticle = destinationArticle.replaceAll('_', ' ');
// If a Fextralife wiki, replace plus signs with spaces
// When there are multiple plus signs together, this regex will only replace only the first
if (matchingSite['origin_base_url'].includes('.wiki.fextralife.com')) {
destinationArticle = destinationArticle.replace(/(?<!\+)\+/g, ' ');
}
// Encode article
destinationArticle = encodeURIComponent(destinationArticle);
let searchParams = '';
switch (matchingSite['destination_platform']) {
case 'mediawiki':
searchParams = '?search=' + destinationArticle;
break;
case 'doku':
searchParams = 'start?do=search&q=' + destinationArticle;
break;
}
newURL = 'https://' + matchingSite["destination_base_url"] + matchingSite["destination_search_path"] + searchParams;
} else {
newURL = 'https://' + matchingSite["destination_base_url"];
}
// When head elem is loaded, notify that another wiki is available
const docObserver = new MutationObserver((mutations, mutationInstance) => {
const headElement = document.querySelector('head');
if (headElement) {
try {
displayRedirectBanner(newURL, matchingSite['id'], matchingSite['destination'], matchingSite['language'], matchingSite['tags'], storage);
} finally {
mutationInstance.disconnect();
}
}
});
docObserver.observe(document, {
childList: true,
subtree: true
});
}
}
});

View File

@ -25,41 +25,6 @@ function addLocationObserver(callback) {
observer.observe(document.body, config);
}
// Load website data:
async function getData() {
let sites = [];
let promises = [];
for (let i = 0; i < LANGS.length; i++) {
promises.push(fetch(chrome.runtime.getURL('data/sites' + LANGS[i] + '.json'))
.then((resp) => resp.json())
.then((jsonData) => {
jsonData.forEach((site) => {
site.origins.forEach((origin) => {
sites.push({
"id": site.id,
"origin": origin.origin,
"origin_group": site.origins_label,
"origin_base_url": origin.origin_base_url,
"origin_content_path": origin.origin_content_path,
"origin_main_page": origin.origin_main_page,
"destination": site.destination,
"destination_base_url": site.destination_base_url,
"destination_search_path": site.destination_search_path,
"destination_content_prefix": origin.destination_content_prefix || site.destination_content_prefix || "",
"destination_platform": site.destination_platform,
"destination_icon": site.destination_icon,
"destination_main_page": site.destination_main_page,
"lang": LANGS[i]
})
})
});
}));
}
await Promise.all(promises);
return sites;
}
function insertCSS() {
// Output CSS
styleString = `
@ -253,18 +218,18 @@ function replaceSearchResults(searchResultContainer, site, link) {
indieResultFavicon.alt = '';
indieResultFavicon.width = '12';
indieResultFavicon.height = '12';
indieResultFavicon.src = chrome.runtime.getURL('favicons/' + site.lang.toLowerCase() + '/' + site.destination_icon);
indieResultFavicon.src = chrome.runtime.getURL('favicons/' + site.language.toLowerCase() + '/' + site.destination_icon);
indieResultFaviconContainer.append(indieResultFavicon);
let indieResultText = document.createElement('span');
if (originArticle && originArticle !== site['origin_main_page']) {
destinationArticleTitle = destinationArticle.replace(site['destination_content_prefix'], '').replaceAll('_', ' ');
if (site['lang'] === 'EN' && link.match(/fandom\.com\/[a-z]{2}\/wiki\//)) {
if (site['language'] === 'EN' && link.match(/fandom\.com\/[a-z]{2}\/wiki\//)) {
indieResultText.innerText = 'Look up "' + decodeURIComponent(decodeURIComponent(destinationArticleTitle)) + '" on ' + site.destination + ' (EN)';
} else {
indieResultText.innerText = 'Look up "' + decodeURIComponent(decodeURIComponent(destinationArticleTitle)) + '" on ' + site.destination;
}
} else {
if (site['lang'] === 'EN' && link.match(/fandom\.com\/[a-z]{2}\/wiki\//)) {
if (site['language'] === 'EN' && link.match(/fandom\.com\/[a-z]{2}\/wiki\//)) {
indieResultText.innerText = 'Visit ' + site.destination + ' (EN) instead';
} else {
indieResultText.innerText = 'Visit ' + site.destination + ' instead';
@ -411,8 +376,7 @@ function hideSearchResults(searchResultContainer, searchEngine, site, showBanner
}
function filterSearchResults(searchResults, searchEngine, storage) {
getData().then(sites => {
let crossLanguageSetting = storage.crossLanguage || 'off';
commonFunctionGetSiteDataByOrigin().then(async sites => {
let countFiltered = 0;
for (let searchResult of searchResults) {
@ -437,86 +401,71 @@ function filterSearchResults(searchResults, searchEngine, storage) {
}
}
// Check if site is in our list of wikis:
if (crossLanguageSetting === 'on') {
matchingSites = sites.filter(el => link.replace(/.*https?:\/\//, '').startsWith(el.origin_base_url));
} else {
matchingSites = sites.filter(el => link.replace(/.*https?:\/\//, '') === (el.origin_base_url));
matchingSites = matchingSites.concat(sites.filter(el => link.replace(/.*https?:\/\//, '').startsWith(el.origin_base_url + el.origin_content_path)));
}
if (matchingSites.length > 0) {
// Select match with longest base URL
let closestMatch = "";
matchingSites.forEach(site => {
if (site.origin_base_url.length > closestMatch.length) {
closestMatch = site.origin_base_url;
}
});
let site = matchingSites.find(site => site.origin_base_url === closestMatch);
if (site) {
// Get user's settings for the wiki
let id = site['id'];
let searchFilterSetting = 'replace';
if (storage.searchEngineSettings && storage.searchEngineSettings[id]) {
searchFilterSetting = storage.searchEngineSettings[id];
} else if (storage.defaultSearchAction) {
searchFilterSetting = storage.defaultSearchAction;
let crossLanguageSetting = storage.crossLanguage || 'off';
let matchingSite = await commonFunctionFindMatchingSite(link, crossLanguageSetting);
if (matchingSite) {
// Get user's settings for the wiki
let id = matchingSite['id'];
let searchFilterSetting = 'replace';
if (storage.searchEngineSettings && storage.searchEngineSettings[id]) {
searchFilterSetting = storage.searchEngineSettings[id];
} else if (storage.defaultSearchAction) {
searchFilterSetting = storage.defaultSearchAction;
}
if (searchFilterSetting !== 'disabled') {
// Output stylesheet if not already done
if (filteredWikis.length === 0) {
// Wait for head to be available
const headElement = document.querySelector('head');
if (headElement && !document.querySelector('.iwb-styles')) {
insertCSS();
} else {
const docObserver = new MutationObserver((mutations, mutationInstance) => {
const headElement = document.querySelector('head');
if (headElement && !document.querySelector('.iwb-styles')) {
insertCSS();
mutationInstance.disconnect();
}
});
docObserver.observe(document, {
childList: true,
subtree: true
});
}
}
if (searchFilterSetting !== 'disabled') {
// Output stylesheet if not already done
if (filteredWikis.length === 0) {
// Wait for head to be available
const headElement = document.querySelector('head');
if (headElement && !document.querySelector('.iwb-styles')) {
insertCSS();
} else {
const docObserver = new MutationObserver((mutations, mutationInstance) => {
const headElement = document.querySelector('head');
if (headElement && !document.querySelector('.iwb-styles')) {
insertCSS();
mutationInstance.disconnect();
}
});
docObserver.observe(document, {
childList: true,
subtree: true
});
}
}
let searchResultContainer = null;
switch (searchEngine) {
case 'google':
searchResultContainer = searchResult.closest('div[data-hveid].g') || searchResult.closest('div[data-hveid]');
break;
case 'bing':
searchResultContainer = searchResult.closest('li.b_algo');
break;
case 'duckduckgo':
searchResultContainer = searchResult.closest('li[data-layout], div.web-result');
break;
case 'brave':
searchResultContainer = searchResult.closest('div.snippet');
break;
case 'ecosia':
searchResultContainer = searchResult.closest('div.mainline__result-wrapper article div.result__body');
break;
case 'startpage':
searchResultContainer = searchResult.closest('div.w-gl__result');
break;
case 'yahoo':
searchResultContainer = searchResult.closest('#web > ol > li div.itm .exp, #web > ol > li div.algo, #web > ol > li, section.algo');
break;
default:
}
let searchResultContainer = null;
switch (searchEngine) {
case 'google':
searchResultContainer = searchResult.closest('div[data-hveid].g') || searchResult.closest('div[data-hveid]');
break;
case 'bing':
searchResultContainer = searchResult.closest('li.b_algo');
break;
case 'duckduckgo':
searchResultContainer = searchResult.closest('li[data-layout], div.web-result');
break;
case 'brave':
searchResultContainer = searchResult.closest('div.snippet');
break;
case 'ecosia':
searchResultContainer = searchResult.closest('div.mainline__result-wrapper article div.result__body');
break;
case 'startpage':
searchResultContainer = searchResult.closest('div.w-gl__result');
break;
case 'yahoo':
searchResultContainer = searchResult.closest('#web > ol > li div.itm .exp, #web > ol > li div.algo, #web > ol > li, section.algo');
break;
default:
}
if (searchResultContainer) {
if (searchFilterSetting === 'hide') {
countFiltered += hideSearchResults(searchResultContainer, searchEngine, site, storage['hiddenResultsBanner']);
} else {
countFiltered += replaceSearchResults(searchResultContainer, site, link);
}
if (searchResultContainer) {
if (searchFilterSetting === 'hide') {
countFiltered += hideSearchResults(searchResultContainer, searchEngine, matchingSite, storage['hiddenResultsBanner']);
} else {
countFiltered += replaceSearchResults(searchResultContainer, matchingSite, link);
}
}
}

View File

@ -251,6 +251,7 @@
"https://www.google.cat/search*"
],
"js": [
"common-functions-general.js",
"content-search-filtering.js"
],
"run_at": "document_start"
@ -273,6 +274,7 @@
"https://breeze.whateveritworks.org/*"
],
"js": [
"common-functions-general.js",
"content-banners.js"
],
"run_at": "document_start"
@ -293,6 +295,7 @@
"https://breeze.whateveritworks.org/*"
],
"js": [
"common-functions-general.js",
"content-breezewiki.js"
],
"run_at": "document_end"

View File

@ -6,21 +6,7 @@
"storage",
"webRequest",
"notifications",
"scripting",
"https://*.fandom.com/*",
"https://*.fextralife.com/*",
"https://breezewiki.com/*",
"https://antifandom.com/*",
"https://bw.projectsegfau.lt/*",
"https://breeze.hostux.net/*",
"https://breezewiki.pussthecat.org/*",
"https://bw.vern.cc/*",
"https://breezewiki.esmailelbob.xyz/*",
"https://bw.artemislena.eu/*",
"https://bw.hamstro.dev/*",
"https://nerd.whatever.social/*",
"https://breeze.nohost.network/*",
"https://breeze.whateveritworks.org/*"
"scripting"
],
"icons": {
"16": "images/logo-16.png",
@ -29,7 +15,7 @@
"64": "images/logo-64.png",
"128": "images/logo-128.png"
},
"browser_action": {
"action": {
"default_popup": "popup.html",
"default_icon": {
"16": "images/logo-16.png",
@ -40,69 +26,34 @@
}
},
"web_accessible_resources": [
"favicons/*",
"data/sitesDE.json",
"data/sitesEN.json",
"data/sitesES.json",
"data/sitesFR.json",
"data/sitesIT.json",
"data/sitesKO.json",
"data/sitesPL.json",
"data/sitesPT.json",
"data/sitesRU.json",
"data/sitesTOK.json",
"data/sitesUK.json",
"data/sitesZH.json"
{
"resources": [
"favicons/*",
"data/sitesDE.json",
"data/sitesEN.json",
"data/sitesES.json",
"data/sitesFR.json",
"data/sitesIT.json",
"data/sitesKO.json",
"data/sitesPL.json",
"data/sitesPT.json",
"data/sitesRU.json",
"data/sitesTOK.json",
"data/sitesUK.json",
"data/sitesZH.json"
],
"matches": [
"https://*/*"
]
}
],
"background": {
"scripts": [
"common-functions-general.js",
"background.js"
],
"persistent": true
]
},
"content_scripts": [
{
"matches": [
"https://*.fandom.com/*",
"https://*.fextralife.com/*",
"https://breezewiki.com/*",
"https://antifandom.com/*",
"https://bw.projectsegfau.lt/*",
"https://breeze.hostux.net/*",
"https://breezewiki.pussthecat.org/*",
"https://bw.vern.cc/*",
"https://breezewiki.esmailelbob.xyz/*",
"https://bw.artemislena.eu/*",
"https://bw.hamstro.dev/*",
"https://nerd.whatever.social/*",
"https://breeze.nohost.network/*",
"https://breeze.whateveritworks.org/*"
],
"js": [
"content-banners.js"
],
"run_at": "document_start"
},
{
"matches": [
"https://breezewiki.com/*",
"https://antifandom.com/*",
"https://bw.projectsegfau.lt/*",
"https://breeze.hostux.net/*",
"https://breezewiki.pussthecat.org/*",
"https://bw.vern.cc/*",
"https://breezewiki.esmailelbob.xyz/*",
"https://bw.artemislena.eu/*",
"https://bw.hamstro.dev/*",
"https://nerd.whatever.social/*",
"https://breeze.nohost.network/*",
"https://breeze.whateveritworks.org/*"
],
"js": [
"content-breezewiki.js"
],
"run_at": "document_end"
},
{
"matches": [
"https://*.bing.com/search*",
@ -303,16 +254,76 @@
"https://www.google.cat/search*"
],
"js": [
"common-functions-general.js",
"content-search-filtering.js"
],
"run_at": "document_start"
},
{
"matches": [
"https://*.fandom.com/*",
"https://*.fextralife.com/*",
"https://breezewiki.com/*",
"https://antifandom.com/*",
"https://bw.projectsegfau.lt/*",
"https://breeze.hostux.net/*",
"https://breezewiki.pussthecat.org/*",
"https://bw.vern.cc/*",
"https://breezewiki.esmailelbob.xyz/*",
"https://bw.artemislena.eu/*",
"https://bw.hamstro.dev/*",
"https://nerd.whatever.social/*",
"https://breeze.nohost.network/*",
"https://breeze.whateveritworks.org/*"
],
"js": [
"common-functions-general.js",
"content-banners.js"
],
"run_at": "document_start"
},
{
"matches": [
"https://breezewiki.com/*",
"https://antifandom.com/*",
"https://bw.projectsegfau.lt/*",
"https://breeze.hostux.net/*",
"https://breezewiki.pussthecat.org/*",
"https://bw.vern.cc/*",
"https://breezewiki.esmailelbob.xyz/*",
"https://bw.artemislena.eu/*",
"https://bw.hamstro.dev/*",
"https://nerd.whatever.social/*",
"https://breeze.nohost.network/*",
"https://breeze.whateveritworks.org/*"
],
"js": [
"content-breezewiki.js"
],
"run_at": "document_end"
}
],
"host_permissions": [
"https://*.fandom.com/*",
"https://*.fextralife.com/*",
"https://breezewiki.com/*",
"https://antifandom.com/*",
"https://bw.projectsegfau.lt/*",
"https://breeze.hostux.net/*",
"https://breezewiki.pussthecat.org/*",
"https://bw.vern.cc/*",
"https://breezewiki.esmailelbob.xyz/*",
"https://bw.artemislena.eu/*",
"https://bw.hamstro.dev/*",
"https://nerd.whatever.social/*",
"https://breeze.nohost.network/*",
"https://breeze.whateveritworks.org/*"
],
"optional_permissions": ["https://*/*"],
"applications": {
"browser_specific_settings": {
"gecko": {
"id": "{cb31ec5d-c49a-4e5a-b240-16c767444f62}"
}
},
"manifest_version": 2
"manifest_version": 3
}

View File

@ -191,7 +191,7 @@
.radioGroup.horizontal {
flex-direction: row;
line-height: 1.5rem;
gap: 1em;
gap: .5em;
}
.radioGroup.vertical {
flex-direction: column;
@ -306,7 +306,7 @@
<label>
<input id="defaultWikiActionAlertRadio" type="radio" name="defaultWikiAction" value="alert" />
<img src="images/toggle-alert.png" height="12" alt="" />
Display banner linking to indie wiki
Show banner linking to indie wiki
</label>
<label>
<input id="defaultWikiActionRedirectRadio" type="radio" name="defaultWikiAction" value="redirect" />
@ -377,7 +377,7 @@
</fieldset>
<fieldset id="breezewikiSettings">
<legend>
<span aria-hidden="true"></span> BreezeWiki settings (<a href="https://breezewiki.com/"
<span aria-hidden="true"></span> BreezeWiki alternative frontend for Fandom (<a href="https://breezewiki.com/"
target="_blank">learn&nbsp;more</a>)
</legend>
<div role="radiogroup">
@ -414,6 +414,8 @@
</form>
</div>
</body>
<script type="text/javascript" src="common-functions-general.js"></script>
<script type="text/javascript" src="common-functions-settings.js"></script>
<script type="text/javascript" src="popup.js"></script>
</html>

407
popup.js
View File

@ -13,189 +13,8 @@ function setPower(setting) {
});
}
// Get wiki data from data folder
async function getData() {
var sites = [];
let promises = [];
for (let i = 0; i < LANGS.length; i++) {
promises.push(fetch(chrome.runtime.getURL('data/sites' + LANGS[i] + '.json'))
.then((resp) => resp.json())
.then((jsonData) => {
jsonData.forEach((site) => site.language = LANGS[i]);
sites = sites.concat(jsonData);
}));
}
await Promise.all(promises);
return sites;
}
async function migrateData() {
await chrome.storage.sync.get(async (storage) => {
if (!storage.v3migration) {
let defaultWikiAction = storage.defaultWikiAction || 'alert';
let defaultSearchAction = storage.defaultSearchAction || 'replace';
// Set new default action settings:
if (!storage.defaultWikiAction) {
if (storage.defaultActionSettings && storage.defaultActionSettings['EN']) {
defaultWikiAction = storage.defaultActionSettings['EN'];
}
chrome.storage.sync.set({ 'defaultWikiAction': defaultWikiAction });
}
if (!storage.defaultSearchAction) {
if (storage.defaultSearchFilterSettings && storage.defaultSearchFilterSettings['EN']) {
if (storage.defaultSearchFilterSettings['EN'] === 'false') {
defaultSearchAction = 'disabled';
} else {
defaultSearchAction = 'replace';
}
}
chrome.storage.sync.set({ 'defaultSearchAction': defaultSearchAction });
}
// Remove old objects:
chrome.storage.sync.remove('defaultActionSettings');
chrome.storage.sync.remove('defaultSearchFilterSettings');
// Migrate wiki settings to new searchEngineSettings and wikiSettings objects
sites = await getData();
let siteSettings = storage.siteSettings || {};
let searchEngineSettings = storage.searchEngineSettings || {};
let wikiSettings = storage.wikiSettings || {};
sites.forEach((site) => {
if (!searchEngineSettings[site.id]) {
if (siteSettings[site.id] && siteSettings[site.id].searchFilter) {
if (siteSettings[site.id].searchFilter === 'false') {
searchEngineSettings[site.id] = 'disabled';
} else {
searchEngineSettings[site.id] = 'replace';
}
} else {
searchEngineSettings[site.id] = defaultSearchAction;
}
}
if (!wikiSettings[site.id]) {
wikiSettings[site.id] = siteSettings[site.id]?.action || defaultWikiAction;
}
});
chrome.storage.sync.set({ 'searchEngineSettings': searchEngineSettings });
chrome.storage.sync.set({ 'wikiSettings': wikiSettings });
// Remove old object:
chrome.storage.sync.remove('siteSettings');
// Mark v3 migration as complete:
chrome.storage.sync.set({ 'v3migration': 'done' });
}
});
}
function populateBreezewikiHosts(breezewikiHosts, selectedHost, customHostName) {
// Populate dropdown selection of hosts
const breezewikiHostSelect = document.getElementById('breezewikiHostSelect');
while (breezewikiHostSelect.firstChild) {
// Remove any existing options
breezewikiHostSelect.removeChild(breezewikiHostSelect.firstChild);
}
// Add known BreezeWiki domains:
for (var i = 0; i < breezewikiHosts.length; i++) {
let option = document.createElement('option');
option.value = breezewikiHosts[i].instance;
let textContent = breezewikiHosts[i].instance.replace('https://', '');
const numberOfPeriods = (textContent.match(/\./g) || []).length;
if (numberOfPeriods > 1) {
textContent = textContent.substring(textContent.indexOf('.') + 1);
}
option.textContent = textContent;
breezewikiHostSelect.appendChild(option);
}
// Add custom BreezeWiki host option:
let customOption = document.createElement('option');
customOption.value = 'CUSTOM';
customOption.textContent = 'Custom host...';
breezewikiHostSelect.appendChild(customOption);
breezewikiHostSelect.value = selectedHost;
// Set up custom domain input:
if (breezewikiHostSelect.value === 'CUSTOM') {
document.getElementById('breezewikiCustomHost').style.display = 'block';
} else {
document.getElementById('breezewikiCustomHost').style.display = 'none';
}
document.getElementById('customBreezewikiHost').value = customHostName.replace(/^https?:\/\//i, '');
}
// Populate BreezeWiki dropdown when enabled
async function loadBreezewikiOptions() {
// Load BreezeWiki options:
chrome.storage.sync.get(['breezewikiHostOptions', 'breezewikiHostFetchTimestamp', 'breezewikiHost', 'breezewikiCustomHost'], (item) => {
let hostOptions = item.breezewikiHostOptions;
let hostFetchTimestamp = item.breezewikiHostFetchTimestamp;
let host = item.breezewikiHost;
let customHost = item.breezewikiCustomHost || '';
// Fetch and cache list of BreezeWiki hosts if first time,
// or if it has been 24 hrs since last refresh
if (!host || !hostOptions || !hostFetchTimestamp || (Date.now() - 86400000 > hostFetchTimestamp)) {
fetch('https://bw.getindie.wiki/instances.json')
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Indie Wiki Buddy failed to get BreezeWiki data.');
}).then((breezewikiHosts) => {
breezewikiHosts = breezewikiHosts.filter(host =>
chrome.runtime.getManifest().version.localeCompare(host.iwb_version,
undefined,
{ numeric: true, sensitivity: 'base' }
) >= 0
);
// If host isn't set, or currently selected host is no longer available, select random host:
if (!host || !breezewikiHosts.some(item => item.instance === host)) {
// Check if BreezeWiki's main site is available
let breezewikiMain = breezewikiHosts.filter(host => host.instance === 'https://breezewiki.com');
if (breezewikiMain.length > 0) {
host = breezewikiMain[0].instance;
} else {
// If BreezeWiki.com is not available, set to a random mirror
try {
host = breezewikiHosts[Math.floor(Math.random() * breezewikiHosts.length)].instance;
} catch (e) {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
}
}
}
populateBreezewikiHosts(breezewikiHosts, host, customHost);
// Store BreezeWiki host details
chrome.storage.sync.set({ 'breezewikiHost': host });
chrome.storage.sync.set({ 'breezewikiHostOptions': breezewikiHosts });
chrome.storage.sync.set({ 'breezewikiHostFetchTimestamp': Date.now() });
}).catch((e) => {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
// If fetch fails and no host is set, default to breezewiki.com:
if (!host) {
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com' });
}
});
} else {
// If currently selected host is no longer available, select random host:
if (host !== 'CUSTOM' && !hostOptions.some(item => item.instance === host)) {
host = hostOptions[Math.floor(Math.random() * hostOptions.length)].instance;
}
populateBreezewikiHosts(hostOptions, host, customHost);
// Store BreezeWiki host details
chrome.storage.sync.set({ 'breezewikiHost': host });
}
});
commonFunctionMigrateToV3();
}
// Set power setting
@ -218,69 +37,6 @@ function setPower(setting, storeSetting = true) {
});
}
// Set notifications setting
function setNotifications(setting, storeSetting = true) {
if (storeSetting) {
chrome.storage.sync.set({ 'notifications': setting });
}
const notificationsIcon = document.getElementById('notificationsIcon');
if (setting === 'on') {
document.getElementById('notificationsCheckbox').checked = true;
notificationsIcon.innerText = '🔔';
} else {
document.getElementById('notificationsCheckbox').checked = false;
notificationsIcon.innerText = '🔕';
}
}
// Set search results hidden banner setting
function setHiddenResultsBanner(setting, storeSetting = true) {
if (storeSetting) {
chrome.storage.sync.set({ 'hiddenResultsBanner': setting });
}
const hiddenResultsBannerIcon = document.getElementById('hiddenResultsBannerIcon');
if (setting === 'on') {
document.getElementById('hiddenResultsBannerCheckbox').checked = true;
hiddenResultsBannerIcon.innerText = '🔔';
} else {
document.getElementById('hiddenResultsBannerCheckbox').checked = false;
hiddenResultsBannerIcon.innerText = '🔕';
}
}
// Set cross-language setting
function setCrossLanguage(setting, storeSetting = true) {
if (storeSetting) {
chrome.storage.sync.set({ 'crossLanguage': setting });
}
const crossLanguageIcon = document.getElementById('crossLanguageIcon');
if (setting === 'on') {
document.getElementById('crossLanguageCheckbox').checked = true;
crossLanguageIcon.innerText = '🌐';
} else {
document.getElementById('crossLanguageCheckbox').checked = false;
crossLanguageIcon.innerText = '⚪️';
}
}
// Set open changelog setting
function setOpenChangelog(setting, storeSetting = true) {
if (storeSetting) {
chrome.storage.sync.set({ 'openChangelog': setting });
}
const openChangelogIcon = document.getElementById('openChangelogIcon');
if (setting === 'on') {
document.getElementById('openChangelogCheckbox').checked = true;
openChangelogIcon.innerText = '📂';
} else {
document.getElementById('openChangelogCheckbox').checked = false;
openChangelogIcon.innerText = '📁';
}
}
// Set default action setting
chrome.storage.sync.get(['defaultWikiAction'], (item) => {
if (item.defaultWikiAction === 'disabled') {
@ -302,73 +58,6 @@ chrome.storage.sync.get(['defaultSearchAction'], (item) => {
}
});
// Set BreezeWiki settings
function setBreezeWiki(setting, storeSetting = true) {
// Account for legacy BreezeWiki sestting ('on' is now 'redirect')
if (setting === 'on') {
setting = 'redirect';
}
// Store BreezeWiki setting
if (storeSetting) {
chrome.storage.sync.set({ 'breezewiki': setting });
}
// Set BreezeWiki value on radio group
document.options.breezewikiSetting.value = setting;
// Toggle/update host display
const breezewikiHost = document.getElementById('breezewikiHost');
if (setting !== 'off') {
breezewikiHost.style.display = 'block';
chrome.storage.sync.get({ 'breezewikiHost': null }, (host) => {
if (!host.breezewikiHost) {
fetch('https://bw.getindie.wiki/instances.json')
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Indie Wiki Buddy failed to get BreezeWiki data.');
}).then((breezewikiHosts) => {
breezewikiHosts = breezewikiHosts.filter(host =>
chrome.runtime.getManifest().version.localeCompare(host.iwb_version,
undefined,
{ numeric: true, sensitivity: 'base' }
) >= 0
);
// Check if BreezeWiki's main site is available
let breezewikiMain = breezewikiHosts.filter(host => host.instance === 'https://breezewiki.com');
if (breezewikiMain.length > 0) {
host.breezewikiHost = breezewikiMain[0].instance;
} else {
// If BreezeWiki.com is not available, set to a random mirror
try {
host.breezewikiHost = breezewikiHosts[Math.floor(Math.random() * breezewikiHosts.length)].instance;
} catch (e) {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
}
}
chrome.storage.sync.set({ 'breezewikiHost': host.breezewikiHost });
chrome.storage.sync.set({ 'breezewikiHostOptions': breezewikiHosts });
chrome.storage.sync.set({ 'breezewikiHostFetchTimestamp': Date.now() });
document.getElementById('breezewikiHostSelect').value = host.breezewikiHost;
}).catch((e) => {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
// If fetch fails and no host is set, default to breezewiki.com:
if (!host) {
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com' });
}
});
} else {
document.getElementById('breezewikiHostSelect').value = host.breezewikiHost;
}
});
} else {
breezewikiHost.style.display = 'none';
}
}
// Main function that runs on-load
document.addEventListener('DOMContentLoaded', () => {
// If running Opera, show note about search engine access
@ -395,94 +84,8 @@ document.addEventListener('DOMContentLoaded', () => {
chrome.tabs.create({ 'url': chrome.runtime.getURL('settings.html') });
window.close();
});
// Set setting toggle values:
chrome.storage.local.get({ 'power': 'on' }, (item) => {
setPower(item.power, false);
});
chrome.storage.sync.get({ 'notifications': 'on' }, (item) => {
setNotifications(item.notifications, false);
});
chrome.storage.sync.get({ 'hiddenResultsBanner': 'on' }, (item) => {
setHiddenResultsBanner(item.hiddenResultsBanner, false);
});
chrome.storage.sync.get({ 'crossLanguage': 'off' }, (item) => {
setCrossLanguage(item.crossLanguage, false);
});
chrome.storage.sync.get({ 'openChangelog': 'off' }, (item) => {
setOpenChangelog(item.openChangelog, false);
});
chrome.storage.sync.get({ 'breezewiki': 'off' }, (item) => {
// Account for legacy 'on' setting for BreezeWiki
if (item.breezewiki === 'on') {
setBreezeWiki('redirect');
} else {
setBreezeWiki(item.breezewiki, false);
}
// Load BreezeWiki options if BreezeWiki is enabled
if (item.breezewiki !== 'off') {
loadBreezewikiOptions();
}
});
// Add event listeners for general setting toggles
document.getElementById('powerCheckbox').addEventListener('change', () => {
chrome.storage.local.get({ 'power': 'on' }, (item) => {
if (item.power === 'on') {
setPower('off');
} else {
setPower('on');
}
});
});
document.getElementById('notificationsCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'notifications': 'on' }, (item) => {
if (item.notifications === 'on') {
setNotifications('off');
} else {
setNotifications('on');
}
});
});
document.getElementById('hiddenResultsBannerCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'hiddenResultsBanner': 'on' }, (item) => {
if (item.hiddenResultsBanner === 'on') {
setHiddenResultsBanner('off');
} else {
setHiddenResultsBanner('on');
}
});
});
document.getElementById('crossLanguageCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'crossLanguage': 'off' }, (item) => {
if (item.crossLanguage === 'on') {
setCrossLanguage('off');
} else {
setCrossLanguage('on');
}
});
});
document.getElementById('openChangelogCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'openChangelog': 'off' }, (item) => {
if (item.openChangelog === 'on') {
setOpenChangelog('off');
} else {
setOpenChangelog('on');
}
});
});
document.querySelectorAll('[name="breezewikiSetting"]').forEach((el) => {
el.addEventListener('change', async () => {
const settingValue = document.options.breezewikiSetting.value;
chrome.storage.sync.set({ 'breezewiki': settingValue });
setBreezeWiki(settingValue);
if (settingValue !== 'off') {
loadBreezewikiOptions();
}
});
});
// Add event listener for BreezeWiki host select
const breezewikiHostSelect = document.getElementById('breezewikiHostSelect');
breezewikiHostSelect.addEventListener('change', () => {
if (breezewikiHostSelect.value === 'CUSTOM') {
@ -503,7 +106,7 @@ document.addEventListener('DOMContentLoaded', () => {
chrome.storage.sync.set({ 'defaultWikiAction': document.options.defaultWikiAction.value })
let wikiSettings = {};
sites = await getData();
sites = await commonFunctionGetSiteDataByDestination();
sites.forEach((site) => {
wikiSettings[site.id] = document.options.defaultWikiAction.value;
});
@ -515,7 +118,7 @@ document.addEventListener('DOMContentLoaded', () => {
chrome.storage.sync.set({ 'defaultSearchAction': document.options.defaultSearchAction.value })
let searchEngineSettings = {};
sites = await getData();
sites = await commonFunctionGetSiteDataByDestination();
sites.forEach((site) => {
searchEngineSettings[site.id] = document.options.defaultSearchAction.value;
});

View File

@ -198,7 +198,7 @@
.radioGroup.horizontal {
flex-direction: row;
line-height: 1.5rem;
gap: 1em;
gap: .5em;
}
.radioGroup.vertical {
flex-direction: column;
@ -587,7 +587,7 @@
</fieldset>
<fieldset id="breezewikiSettings">
<legend>
<span aria-hidden="true"></span> BreezeWiki settings (<a href="https://breezewiki.com/"
<span aria-hidden="true"></span> BreezeWiki alternative frontend for Fandom (<a href="https://breezewiki.com/"
target="_blank">learn&nbsp;more</a>)
</legend>
<div role="radiogroup">
@ -785,6 +785,8 @@
</div>
</div>
</body>
<script type="text/javascript" src="common-functions-general.js"></script>
<script type="text/javascript" src="common-functions-settings.js"></script>
<script type="text/javascript" src="settings.js"></script>
</html>

View File

@ -25,130 +25,9 @@ function resetOptions() {
document.getElementById('setAllSearchEngineReplace').cloneNode(true);
}
// Get wiki data from data folder
async function getData() {
let sites = [];
let promises = [];
for (let i = 0; i < LANGS.length; i++) {
promises.push(fetch(chrome.runtime.getURL('data/sites' + LANGS[i] + '.json'))
.then((resp) => resp.json())
.then((jsonData) => {
jsonData.forEach((site) => site.language = LANGS[i]);
sites = sites.concat(jsonData);
}));
}
await Promise.all(promises);
return sites;
}
function populateBreezewikiHosts(breezewikiHosts, selectedHost, customHostName) {
// Populate dropdown selection of hosts
const breezewikiHostSelect = document.getElementById('breezewikiHostSelect');
while (breezewikiHostSelect.firstChild) {
// Remove any existing options
breezewikiHostSelect.removeChild(breezewikiHostSelect.firstChild);
}
// Add known BreezeWiki domains:
for (var i = 0; i < breezewikiHosts.length; i++) {
let option = document.createElement('option');
option.value = breezewikiHosts[i].instance;
let textContent = breezewikiHosts[i].instance.replace('https://', '');
const numberOfPeriods = (textContent.match(/\./g) || []).length;
if (numberOfPeriods > 1) {
textContent = textContent.substring(textContent.indexOf('.') + 1);
}
option.textContent = textContent;
breezewikiHostSelect.appendChild(option);
}
// Add custom BreezeWiki host option:
let customOption = document.createElement('option');
customOption.value = 'CUSTOM';
customOption.textContent = 'Custom host...';
breezewikiHostSelect.appendChild(customOption);
breezewikiHostSelect.value = selectedHost;
// Set up custom domain input:
if (breezewikiHostSelect.value === 'CUSTOM') {
document.getElementById('breezewikiCustomHost').style.display = 'block';
} else {
document.getElementById('breezewikiCustomHost').style.display = 'none';
}
document.getElementById('customBreezewikiHost').value = customHostName.replace(/^https?:\/\//i, '');
}
// Populate BreezeWiki dropdown when enabled
async function loadBreezewikiOptions() {
// Load BreezeWiki options:
chrome.storage.sync.get(['breezewikiHostOptions', 'breezewikiHostFetchTimestamp', 'breezewikiHost', 'breezewikiCustomHost'], (item) => {
let hostOptions = item.breezewikiHostOptions;
let hostFetchTimestamp = item.breezewikiHostFetchTimestamp;
let host = item.breezewikiHost;
let customHost = item.breezewikiCustomHost || '';
// Fetch and cache list of BreezeWiki hosts if first time,
// or if it has been 24 hrs since last refresh
if (!host || !hostOptions || !hostFetchTimestamp || (Date.now() - 86400000 > hostFetchTimestamp)) {
fetch('https://bw.getindie.wiki/instances.json')
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Indie Wiki Buddy failed to get BreezeWiki data.');
}).then((breezewikiHosts) => {
breezewikiHosts = breezewikiHosts.filter(host =>
chrome.runtime.getManifest().version.localeCompare(host.iwb_version,
undefined,
{ numeric: true, sensitivity: 'base' }
) >= 0
);
// If host isn't set, or currently selected host is no longer available, select random host:
if (!host || !breezewikiHosts.some(item => item.instance === host)) {
// Check if BreezeWiki's main site is available
let breezewikiMain = breezewikiHosts.filter(host => host.instance === 'https://breezewiki.com');
if (breezewikiMain.length > 0) {
host = breezewikiMain[0].instance;
} else {
// If BreezeWiki.com is not available, set to a random mirror
try {
host = breezewikiHosts[Math.floor(Math.random() * breezewikiHosts.length)].instance;
} catch (e) {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
}
}
}
populateBreezewikiHosts(breezewikiHosts, host, customHost);
// Store BreezeWiki host details
chrome.storage.sync.set({ 'breezewikiHost': host });
chrome.storage.sync.set({ 'breezewikiHostOptions': breezewikiHosts });
chrome.storage.sync.set({ 'breezewikiHostFetchTimestamp': Date.now() });
}).catch((e) => {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
// If fetch fails and no host is set, default to breezewiki.com:
if (!host) {
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com' });
}
});
} else {
// If currently selected host is no longer available, select random host:
if (host !== 'CUSTOM' && !hostOptions.some(item => item.instance === host)) {
host = hostOptions[Math.floor(Math.random() * hostOptions.length)].instance;
}
populateBreezewikiHosts(hostOptions, host, customHost);
// Store BreezeWiki host details
chrome.storage.sync.set({ 'breezewikiHost': host });
}
});
}
// Populate settings and toggles
async function loadOptions(lang, textFilter = '') {
sites = await getData();
sites = await commonFunctionGetSiteDataByDestination();
textFilter = textFilter.toLocaleLowerCase();
// Sort sites alphabetically by destination
@ -583,135 +462,8 @@ function setOpenChangelog(setting, storeSetting = true) {
}
}
// Set BreezeWiki settings
function setBreezeWiki(setting, storeSetting = true) {
// Account for legacy BreezeWiki sestting ('on' is now 'redirect')
if (setting === 'on') {
setting = 'redirect';
}
// Store BreezeWiki setting
if (storeSetting) {
chrome.storage.sync.set({ 'breezewiki': setting });
}
// Set BreezeWiki value on radio group
document.options.breezewikiSetting.value = setting;
// Toggle/update host display
const breezewikiHost = document.getElementById('breezewikiHost');
if (setting !== 'off') {
breezewikiHost.style.display = 'block';
chrome.storage.sync.get({ 'breezewikiHost': null }, (host) => {
if (!host.breezewikiHost) {
fetch('https://bw.getindie.wiki/instances.json')
.then((response) => {
if (response.ok) {
return response.json();
}
throw new Error('Indie Wiki Buddy failed to get BreezeWiki data.');
}).then((breezewikiHosts) => {
breezewikiHosts = breezewikiHosts.filter(host =>
chrome.runtime.getManifest().version.localeCompare(host.iwb_version,
undefined,
{ numeric: true, sensitivity: 'base' }
) >= 0
);
// Check if BreezeWiki's main site is available
let breezewikiMain = breezewikiHosts.filter(host => host.instance === 'https://breezewiki.com');
if (breezewikiMain.length > 0) {
host.breezewikiHost = breezewikiMain[0].instance;
} else {
// If BreezeWiki.com is not available, set to a random mirror
try {
host.breezewikiHost = breezewikiHosts[Math.floor(Math.random() * breezewikiHosts.length)].instance;
} catch (e) {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
}
}
chrome.storage.sync.set({ 'breezewikiHost': host.breezewikiHost });
chrome.storage.sync.set({ 'breezewikiHostOptions': breezewikiHosts });
chrome.storage.sync.set({ 'breezewikiHostFetchTimestamp': Date.now() });
document.getElementById('breezewikiHostSelect').value = host.breezewikiHost;
}).catch((e) => {
console.log('Indie Wiki Buddy failed to get BreezeWiki data: ' + e);
// If fetch fails and no host is set, default to breezewiki.com:
if (!host) {
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com' });
}
});
} else {
document.getElementById('breezewikiHostSelect').value = host.breezewikiHost;
}
});
} else {
breezewikiHost.style.display = 'none';
}
}
async function migrateData() {
await chrome.storage.sync.get(async (storage) => {
if (!storage.v3migration) {
let defaultWikiAction = storage.defaultWikiAction || 'alert';
let defaultSearchAction = storage.defaultSearchAction || 'replace';
// Set new default action settings:
if (!storage.defaultWikiAction) {
if (storage.defaultActionSettings && storage.defaultActionSettings['EN']) {
defaultWikiAction = storage.defaultActionSettings['EN'];
}
chrome.storage.sync.set({ 'defaultWikiAction': defaultWikiAction });
}
if (!storage.defaultSearchAction) {
if (storage.defaultSearchFilterSettings && storage.defaultSearchFilterSettings['EN']) {
if (storage.defaultSearchFilterSettings['EN'] === 'false') {
defaultSearchAction = 'disabled';
} else {
defaultSearchAction = 'replace';
}
}
chrome.storage.sync.set({ 'defaultSearchAction': defaultSearchAction });
}
// Remove old objects:
chrome.storage.sync.remove('defaultActionSettings');
chrome.storage.sync.remove('defaultSearchFilterSettings');
// Migrate wiki settings to new searchEngineSettings and wikiSettings objects
sites = await getData();
let siteSettings = storage.siteSettings || {};
let searchEngineSettings = storage.searchEngineSettings || {};
let wikiSettings = storage.wikiSettings || {};
sites.forEach((site) => {
if (!searchEngineSettings[site.id]) {
if (siteSettings[site.id] && siteSettings[site.id].searchFilter) {
if (siteSettings[site.id].searchFilter === 'false') {
searchEngineSettings[site.id] = 'disabled';
} else {
searchEngineSettings[site.id] = 'replace';
}
} else {
searchEngineSettings[site.id] = defaultSearchAction;
}
}
if (!wikiSettings[site.id]) {
wikiSettings[site.id] = siteSettings[site.id]?.action || defaultWikiAction;
}
});
chrome.storage.sync.set({ 'searchEngineSettings': searchEngineSettings });
chrome.storage.sync.set({ 'wikiSettings': wikiSettings });
// Remove old object:
chrome.storage.sync.remove('siteSettings');
// Mark v3 migration as complete:
chrome.storage.sync.set({ 'v3migration': 'done' });
}
});
commonFunctionMigrateToV3();
}
// Main function that runs on-load
@ -784,93 +536,7 @@ document.addEventListener('DOMContentLoaded', () => {
loadOptions(langSelect.value, filterInput);
});
// Set setting toggle values:
chrome.storage.local.get({ 'power': 'on' }, (item) => {
setPower(item.power, false);
});
chrome.storage.sync.get({ 'notifications': 'on' }, (item) => {
setNotifications(item.notifications, false);
});
chrome.storage.sync.get({ 'hiddenResultsBanner': 'on' }, (item) => {
setHiddenResultsBanner(item.hiddenResultsBanner, false);
});
chrome.storage.sync.get({ 'crossLanguage': 'off' }, (item) => {
setCrossLanguage(item.crossLanguage, false);
});
chrome.storage.sync.get({ 'openChangelog': 'off' }, (item) => {
setOpenChangelog(item.openChangelog, false);
});
chrome.storage.sync.get({ 'breezewiki': 'off' }, (item) => {
// Account for legacy 'on' setting for BreezeWiki
if (item.breezewiki === 'on') {
setBreezeWiki('redirect');
} else {
setBreezeWiki(item.breezewiki, false);
}
// Load BreezeWiki options if BreezeWiki is enabled
if (item.breezewiki !== 'off') {
loadBreezewikiOptions();
}
});
// Add event listeners for general setting toggles
document.getElementById('powerCheckbox').addEventListener('change', () => {
chrome.storage.local.get({ 'power': 'on' }, (item) => {
if (item.power === 'on') {
setPower('off');
} else {
setPower('on');
}
});
});
document.getElementById('notificationsCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'notifications': 'on' }, (item) => {
if (item.notifications === 'on') {
setNotifications('off');
} else {
setNotifications('on');
}
});
});
document.getElementById('hiddenResultsBannerCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'hiddenResultsBanner': 'on' }, (item) => {
if (item.hiddenResultsBanner === 'on') {
setHiddenResultsBanner('off');
} else {
setHiddenResultsBanner('on');
}
});
});
document.getElementById('crossLanguageCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'crossLanguage': 'off' }, (item) => {
if (item.crossLanguage === 'on') {
setCrossLanguage('off');
} else {
setCrossLanguage('on');
}
});
});
document.getElementById('openChangelogCheckbox').addEventListener('change', () => {
chrome.storage.sync.get({ 'openChangelog': 'off' }, (item) => {
if (item.openChangelog === 'on') {
setOpenChangelog('off');
} else {
setOpenChangelog('on');
}
});
});
document.querySelectorAll('[name="breezewikiSetting"]').forEach((el) => {
el.addEventListener('change', async () => {
const settingValue = document.options.breezewikiSetting.value;
chrome.storage.sync.set({ 'breezewiki': settingValue });
setBreezeWiki(settingValue);
if (settingValue !== 'off') {
loadBreezewikiOptions();
}
});
});
// Add event listener for BreezeWiki host select
const breezewikiHostSelect = document.getElementById('breezewikiHostSelect');
breezewikiHostSelect.addEventListener('change', () => {
if (breezewikiHostSelect.value === 'CUSTOM') {