Adding ability to redirect non-EN Fandom wikis to EN / Quick fix for pre-rendered webRequests

pull/327/head
Kevin Payravi 2023-11-05 00:52:22 -05:00
parent fe9a4a134b
commit 333ebd71e7
6 changed files with 482 additions and 395 deletions

View File

@ -1,9 +1,11 @@
// Capture web requests
chrome.webRequest.onBeforeSendHeaders.addListener(
function (event) {
if (event.documentLifecycle !== 'prerender') {
main(event);
}
},
{ urls: ['*://*.fandom.com/*', '*://*.wiki.fextralife.com/*'], types: ['main_frame'] }
{ urls: ['*://*.fandom.com/*', '*://*.wiki.fextralife.com/*'], types: ['main_frame', 'sub_frame'] }
);
// Listen for user turning extension on or off, to update icon
@ -324,10 +326,13 @@ async function getData() {
async function main(eventInfo) {
// Store tab URL and remove any search parameters and section anchors
const url = new URL(eventInfo.url.replace(/(\?|#).*/i, ''));
let url = '';
if (eventInfo.type === 'main_frame') {
url = new URL(eventInfo.url.replace(/(\?|#).*/i, ''));
} else {
url = new URL(eventInfo.initiator);
}
// Check for Fandom or Fextralife in hostname and quit early if not
if (eventInfo.documentLifecycle !== 'prerender') {
// Create object prototypes for getting and setting attributes
Object.prototype.get = function (prop) {
this[prop] = this[prop] || {};
@ -347,8 +352,14 @@ async function main(eventInfo) {
chrome.storage.sync.get(function (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 = sites.filter(el => url.href.replace(/^https?:\/\//, '').startsWith(el.origin_base_url));
let matchingSites = [];
if (crossLanguageSetting === 'on') {
matchingSites = sites.filter(el => url.href.replace(/^https?:\/\//, '').startsWith(el.origin_base_url));
} else {
matchingSites = sites.filter(el => url.href.replace(/^https?:\/\//, '').startsWith(el.origin_base_url + el.origin_content_path));
}
if (matchingSites.length > 0) {
// Select match with longest base URL
let closestMatch = "";
@ -370,7 +381,6 @@ async function main(eventInfo) {
// Instead, we take everything after the wiki's base URL + content path
let article = url.href.split(site['origin_base_url'] + site['origin_content_path'])[1];
// Set up URL to redirect user to based on wiki platform
if (article || (!article && !url.href.split(site['origin_base_url'] + '/')[1])) {
let newURL = '';
if (article) {
let searchParams = '';
@ -406,7 +416,6 @@ async function main(eventInfo) {
// Self-clear notification after 6 seconds
setTimeout(function () { chrome.notifications.clear(notifID); }, 6000);
}
}
} else if ((storage.breezewiki ?? 'off') === 'on') {
redirectToBreezeWiki(storage, eventInfo, url);
}
@ -417,5 +426,4 @@ async function main(eventInfo) {
}
});
});
}
}

View File

@ -42,7 +42,7 @@ async function getData() {
return sites;
}
function displayRedirectBanner(url, id, destination, storage) {
function displayRedirectBanner(origin, newUrl, id, destinationName, destinationLanguage, storage) {
// Output CSS
styleString = `
#indie-wiki-banner {
@ -184,12 +184,16 @@ function displayRedirectBanner(url, id, destination, storage) {
var bannerText = document.createElement('span');
bannerText.classList.add('indie-wiki-banner-big-text');
banner.appendChild(bannerText);
if (destinationLanguage === 'EN' && origin.href.match(/fandom\.com\/[a-z]{2}\/wiki\//)) {
bannerText.textContent = 'There is an independent wiki covering this topic in English!';
} else {
bannerText.textContent = 'There is an independent wiki covering this topic!';
}
var bannerWikiLink = document.createElement('a');
bannerWikiLink.classList.add('indie-wiki-banner-link');
bannerText.appendChild(bannerWikiLink);
bannerWikiLink.href = url;
bannerWikiLink.textContent = 'Visit ' + destination + ' →';
bannerWikiLink.href = newUrl;
bannerWikiLink.textContent = 'Visit ' + destinationName + ' →';
// Function to insert banner into DOM before body element
function addBannerToDOM() {
@ -237,11 +241,18 @@ function main() {
}
}
getData().then(sites => {
let crossLanguageSetting = storage.crossLanguage || 'off';
// Check if site is in our list of wikis:
let matchingSites = sites.filter(el => String(origin).replace(/^https?:\/\//, '').startsWith(el.origin_base_url));
// let matchingSites = sites.filter(el => String(origin).replace(/^https?:\/\//, '').startsWith(el.origin_base_url));
let matchingSites = [];
if (crossLanguageSetting === 'on') {
matchingSites = sites.filter(el => String(origin).replace(/^https?:\/\//, '').startsWith(el.origin_base_url));
} else {
matchingSites = sites.filter(el => String(origin).replace(/^https?:\/\//, '').startsWith(el.origin_base_url + el.origin_content_path));
}
if (matchingSites.length > 0) {
// Select match with longest base URL
let closestMatch = "";
let closestMatch = '';
matchingSites.forEach(site => {
if (site.origin_base_url.length > closestMatch.length) {
closestMatch = site.origin_base_url;
@ -250,17 +261,16 @@ function main() {
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 settings = storage.wikiSettings || {};
let siteSetting = settings[id] || storage.defaultWikiAction || 'alert';
// 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 article = String(origin).split(site['origin_base_url'] + site['origin_content_path'])[1];
let article = String(origin).split(site['origin_content_path'])[1];
// Set up URL to redirect user to based on wiki platform:
if (article || (!article && !url.href.split(site['origin_base_url'] + '/')[1])) {
let newURL = '';
if (article) {
let searchParams = '';
@ -281,7 +291,7 @@ function main() {
const docObserver = new MutationObserver(function (mutations, mutationInstance) {
const headElement = document.querySelector('head');
if (headElement) {
displayRedirectBanner(newURL, site['id'], site['destination'], storage);
displayRedirectBanner(origin, newURL, site['id'], site['destination'], site['lang'], storage);
mutationInstance.disconnect();
}
});
@ -292,7 +302,6 @@ function main() {
}
}
}
}
});
}
}

View File

@ -1,6 +1,7 @@
<!DOCTYPE html>
<html lang="en">
<head>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta charset="UTF-8" />
<title>Indie Wiki Buddy</title>
@ -9,6 +10,7 @@
html {
max-width: 600px;
}
body {
width: max-content;
max-width: min(100%, 600px);
@ -23,6 +25,7 @@
text-decoration-thickness: 1px;
color: #005799;
}
a:visited {
color: #005799;
}
@ -44,6 +47,7 @@
width: 100%;
text-align: center;
}
#openSettings {
background: #3174f1;
border: 1px solid #333333;
@ -53,6 +57,7 @@
margin: 0 .5em .5em .5em;
font-size: 1.3em;
}
#openSettings:hover {
cursor: pointer;
background: #ffffff;
@ -69,6 +74,7 @@
color: #fff;
width: 100%;
}
#header .settingToggle label {
background-color: #fff;
border-radius: 20px;
@ -82,11 +88,13 @@
font-size: .9em;
line-height: 1.3em;
}
#notificationBannerContainer span {
padding: 1em;
display: none;
}
#notificationBannerContainer span ~ span[style] {
#notificationBannerContainer span~span[style] {
border-top: 1px solid #005799;
}
@ -98,7 +106,8 @@
float: right;
padding-top: .2em;
}
#power > label {
#power>label {
display: inline-block;
cursor: pointer;
background-color: #fff;
@ -107,13 +116,15 @@
height: 30px;
text-align: center;
}
#power > input {
#power>input {
height: 0;
width: 0;
margin: 0;
border: none;
appearance: none;
}
#power img {
position: relative;
top: 50%;
@ -139,13 +150,16 @@
user-select: none;
width: 100%;
}
.options .settingToggleContainer {
padding-bottom: 1em;
}
.options .settingToggleContainer:last-child {
padding-bottom: 0;
}
.options .settingToggleContainer > div {
.options .settingToggleContainer>div {
line-height: 1.5rem;
}
@ -156,9 +170,11 @@
vertical-align: middle;
display: inline-block;
}
.settingToggle + div {
.settingToggle+div {
display: inline-block;
}
.settingToggle input,
.settingToggle label {
cursor: pointer;
@ -170,9 +186,9 @@
padding-top: 0.8em;
}
</style>
</head>
</head>
<body>
<body>
<div id="header">
<div id="power">
<input id="powerCheckbox" type="checkbox" />
@ -185,25 +201,34 @@
<div id="content">
<div class="options">
<div class="settingToggleContainer">
<div id="notifications" class="settingToggle">
<div class="settingToggle">
<label>
<input id="notificationsCheckbox" type="checkbox" />
<label for="notificationsCheckbox">
<span id="notificationsText"><span id="notificationsIcon" aria-hidden="true"></span>
Desktop notifications for redirections</span>
<span id="notificationsIcon" aria-hidden="true"></span>
Desktop notifications for
redirections
</label>
</div>
</div>
<div class="settingToggleContainer">
<div id="breezewiki" class="settingToggle">
<div class="settingToggle">
<label>
<input id="crossLanguageCheckbox" type="checkbox" />
<span id="crossLanguageIcon" aria-hidden="true"></span>
Redirect non-English Fandom/Fextralife wikis to
English indie wikis when no same-language wiki exists
</label>
</div>
</div>
<div class="settingToggleContainer">
<div class="settingToggle">
<label>
<input id="breezewikiCheckbox" type="checkbox" />
<label for="breezewikiCheckbox">
<span id="breezewikiText">🌬️ Use BreezeWiki on Fandom (English only)</span>
🌬️ Use BreezeWiki on Fandom (English only)
</label>
</div>
<div>
&nbsp;&nbsp;(<a href="https://breezewiki.com/" target="_blank"
>learn more</a
>)
&nbsp;&nbsp;(<a href="https://breezewiki.com/" target="_blank">learn more</a>)
</div>
<div class="settingToggleContainer">
<div id="breezewikiHost" class="settingToggle">
@ -213,7 +238,7 @@
</div>
</div>
</div>
<hr/>
<hr />
<div id="openSettingsContainer">
<button id="openSettings">
View All Settings
@ -223,40 +248,21 @@
</div>
<hr />
<div id="links">
<a
href="guide.html"
target="_blank"
>Guide</a
>
<a href="guide.html" target="_blank">Guide</a>
&nbsp;&nbsp;&nbsp;
<a
href="https://getindie.wiki/#guide"
target="_blank"
>Website</a
>
<a href="https://getindie.wiki/#guide" target="_blank">Website</a>
&nbsp;&nbsp;&nbsp;
<a
href="https://getindie.wiki/changelog/"
target="_blank"
>Changelog</a
>
<a href="https://getindie.wiki/changelog/" target="_blank">Changelog</a>
&nbsp;&nbsp;&nbsp;
<a
href="https://getindie.wiki/#submit"
target="_blank"
>Submit a Wiki</a
>
<a href="https://getindie.wiki/#submit" target="_blank">Submit a Wiki</a>
&nbsp;&nbsp;&nbsp;
<a
href="https://github.com/KevinPayravi/indie-wiki-buddy"
target="_blank"
>Source Code</a
>
<a href="https://github.com/KevinPayravi/indie-wiki-buddy" target="_blank">Source Code</a>
</div>
</div>
<div id="notificationBannerContainer">
<span id="notificationBannerChromeBug">
Chromium users: Due to a <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=1271154" target="_blank">browser bug</a>,
Chromium users: Due to a <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=1271154"
target="_blank">browser bug</a>,
this extension may stop working after an update. If this happens, try turning the extension off
and on via your browser's extension settings (chrome://extensions/).
<a id="chromeBugHideLink" href="#">Hide this message</a>
@ -268,6 +274,7 @@
<a id="operaPermsHideLink" href="#">Hide this message</a>
</span>
</div>
</body>
<script type="text/javascript" src="popup.js"></script>
</body>
<script type="text/javascript" src="popup.js"></script>
</html>

View File

@ -59,7 +59,7 @@ async function loadBreezeWikiOptions() {
let option = document.createElement('option');
option.value = breezewikiHosts[i].instance;
let textContent = breezewikiHosts[i].instance.replace('https://', '');
const numberOfPeriods = (textContent.match(/\./g)||[]).length;
const numberOfPeriods = (textContent.match(/\./g) || []).length;
if (numberOfPeriods > 1) {
textContent = textContent.substring(textContent.indexOf('.') + 1);
}
@ -78,7 +78,7 @@ async function loadBreezeWikiOptions() {
// If fetch fails and no host is set, default to breezewiki.com:
if (!host) {
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com'});
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com' });
}
});
} else {
@ -96,7 +96,7 @@ async function loadBreezeWikiOptions() {
let option = document.createElement('option');
option.value = hostOptions[i].instance;
let textContent = hostOptions[i].instance.replace('https://', '');
const numberOfPeriods = (textContent.match(/\./g)||[]).length;
const numberOfPeriods = (textContent.match(/\./g) || []).length;
if (numberOfPeriods > 1) {
textContent = textContent.substring(textContent.indexOf('.') + 1);
}
@ -148,6 +148,22 @@ function setNotifications(setting, storeSetting = true) {
}
}
// 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 BreezeWiki settings
function setBreezeWiki(setting, storeSetting = true) {
if (storeSetting) {
@ -197,7 +213,7 @@ function setBreezeWiki(setting, storeSetting = true) {
// If fetch fails and no host is set, default to breezewiki.com:
if (!host) {
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com'});
chrome.storage.sync.set({ 'breezewikiHost': 'https://breezewiki.com' });
}
});
} else {
@ -245,7 +261,7 @@ document.addEventListener('DOMContentLoaded', function () {
// Listener for settings page in new tab:
document.getElementById('openSettings').addEventListener('click', function () {
chrome.tabs.create({'url': chrome.runtime.getURL('settings.html')});
chrome.tabs.create({ 'url': chrome.runtime.getURL('settings.html') });
window.close();
});
@ -256,11 +272,14 @@ document.addEventListener('DOMContentLoaded', function () {
chrome.storage.sync.get({ 'notifications': 'on' }, function (item) {
setNotifications(item.notifications, false);
});
chrome.storage.sync.get({ 'crossLanguage': 'off' }, function (item) {
setCrossLanguage(item.crossLanguage, false);
});
chrome.storage.sync.get({ 'breezewiki': 'off' }, function (item) {
setBreezeWiki(item.breezewiki, false);
// Load BreezeWiki options if BreezeWiki is enabled
if(item.breezewiki === 'on') {
if (item.breezewiki === 'on') {
loadBreezeWikiOptions();
}
});
@ -284,7 +303,15 @@ document.addEventListener('DOMContentLoaded', function () {
}
});
});
document.getElementById('crossLanguageCheckbox').addEventListener('change', function () {
chrome.storage.sync.get({ 'crossLanguage': 'off' }, function (item) {
if (item.crossLanguage === 'on') {
setCrossLanguage('off');
} else {
setCrossLanguage('on');
}
});
});
document.getElementById('breezewikiCheckbox').addEventListener('change', function () {
chrome.storage.sync.get({ 'breezewiki': 'off' }, function (item) {
if (item.breezewiki === 'on') {

View File

@ -492,8 +492,16 @@
<label>
<input id="notificationsCheckbox" type="checkbox" />
<span id="notificationsIcon" aria-hidden="true"></span>
<span id="notificationsText">Desktop notifications for
redirections</span>
Desktop notifications for
redirections
</label>
</div>
<div class="settingToggle">
<label>
<input id="crossLanguageCheckbox" type="checkbox" />
<span id="crossLanguageIcon" aria-hidden="true"></span>
Redirect non-English Fandom/Fextralife wikis to
English wikis when no same-language wiki exists
</label>
</div>
</fieldset>
@ -505,7 +513,7 @@
<div class="settingToggle">
<label>
<input id="breezewikiCheckbox" type="checkbox" />
<span id="breezewikiText">Use BreezeWiki alternative frontend on Fandom (English only)</span>
Use BreezeWiki alternative frontend on Fandom (English only)
</label>
</div>
<div id="breezewikiHost" class="settingToggle">
@ -524,7 +532,7 @@
<img src="images/toggle-disabled.png" width="18" height="18" alt="" /> Do nothing
</div>
<div>
<img src="images/toggle-alert.png" width="18" height="18" alt="" /> Display a banner
<img src="images/toggle-alert.png" width="18" height="18" alt="" /> Display banner
linking to indie wiki
</div>
<div>
@ -619,7 +627,7 @@
</div>
<div>
<input id="defaultWikiActionAlertRadio" type="radio" name="defaultWikiAction" value="alert"
title="Display a banner linking to indie wiki" />
title="Display banner linking to indie wiki" />
<label data-title="Show banner when indie wiki is available" for="defaultWikiActionAlertRadio"></label>
</div>
<div>

View File

@ -525,6 +525,22 @@ function setNotifications(setting, storeSetting = true) {
}
}
// 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 BreezeWiki settings
function setBreezeWiki(setting, storeSetting = true) {
if (storeSetting) {
@ -744,6 +760,9 @@ document.addEventListener('DOMContentLoaded', function () {
chrome.storage.sync.get({ 'notifications': 'on' }, function (item) {
setNotifications(item.notifications, false);
});
chrome.storage.sync.get({ 'crossLanguage': 'off' }, function (item) {
setCrossLanguage(item.crossLanguage, false);
});
chrome.storage.sync.get({ 'breezewiki': 'off' }, function (item) {
setBreezeWiki(item.breezewiki, false);
});
@ -767,6 +786,15 @@ document.addEventListener('DOMContentLoaded', function () {
}
});
});
document.getElementById('crossLanguageCheckbox').addEventListener('change', function () {
chrome.storage.sync.get({ 'crossLanguage': 'off' }, function (item) {
if (item.crossLanguage === 'on') {
setCrossLanguage('off');
} else {
setCrossLanguage('on');
}
});
});
// Add event listeners for BreezeWiki settings
document.getElementById('breezewikiCheckbox').addEventListener('change', function () {