Midora/extension/content.ts

558 lines
19 KiB
TypeScript
Raw Normal View History

2018-09-16 12:27:42 +02:00
var browser = browser || chrome;
var hostname = typeof (location) != 'undefined' ? location.hostname : '';
if (hostname.startsWith('www.')) {
hostname = hostname.substring(4);
}
if (hostname.endsWith('.reddit.com')) hostname = 'reddit.com';
2019-02-25 23:44:34 +01:00
if (hostname.endsWith('.facebook.com')) hostname = 'facebook.com';
if (hostname.endsWith('.youtube.com')) hostname = 'youtube.com';
2018-09-16 12:27:42 +02:00
2018-11-16 21:51:31 +01:00
2018-09-16 12:27:42 +02:00
var myself = null;
2018-11-16 21:51:31 +01:00
2018-12-16 17:36:19 +01:00
function fixupSiteStyles() {
2018-11-16 21:51:31 +01:00
if (hostname == 'reddit.com') {
myself = document.querySelector('#header-bottom-right .user a');
if (!myself) {
var m = document.querySelector('#USER_DROPDOWN_ID');
if (m) {
m = [...m.querySelectorAll('*')].filter(x => x.childNodes.length == 1 && x.firstChild.nodeType == 3).map(x => x.textContent)[0]
if (m) myself = 'reddit.com/user/' + m;
}
2018-09-16 12:27:42 +02:00
}
}
2018-11-16 21:51:31 +01:00
if (hostname == 'facebook.com') {
var m = document.querySelector("[id^='profile_pic_header_']")
if (m) myself = 'facebook.com/' + captureRegex(m.id, /header_(\d+)/);
}
2018-12-16 17:36:19 +01:00
if (hostname == 'medium.com') {
2018-11-16 21:51:31 +01:00
var style = document.createElement('style');
style.textContent = `
a.show-thread-link, a.ThreadedConversation-moreRepliesLink {
color: inherit !important;
}
.fullname,
.stream-item a:hover .fullname,
.stream-item a:active .fullname
{color:inherit;}
`;
document.head.appendChild(style);
2018-10-30 20:56:21 +01:00
2018-11-16 21:51:31 +01:00
}
2018-12-16 17:36:19 +01:00
if (isHostedOn(hostname, 'tumblr.com')) {
2018-12-16 11:32:37 +01:00
var style = document.createElement('style');
style.textContent = `
.assigned-label-transphobic { outline: 2px solid #991515 !important; }
2018-12-16 15:30:12 +01:00
.assigned-label-t-friendly { outline: 1px solid #77B91E !important; }
2018-12-16 11:32:37 +01:00
`;
document.head.appendChild(style);
}
2019-01-13 17:16:37 +01:00
if(hostname.indexOf('wiki') != -1){
var style = document.createElement('style');
style.textContent = `
.assigned-label-transphobic { outline: 1px solid #991515 !important; }
.assigned-label-t-friendly { outline: 1px solid #77B91E !important; }
`;
document.head.appendChild(style);
}
2018-11-16 21:51:31 +01:00
if (hostname == 'twitter.com') {
myself = document.querySelector('.DashUserDropdown-userInfo a');
2018-10-30 20:56:21 +01:00
2018-11-16 21:51:31 +01:00
var style = document.createElement('style');
style.textContent = `
2018-10-30 20:56:21 +01:00
2018-11-16 21:51:31 +01:00
.pretty-link b, .pretty-link s {
color: inherit !important;
}
a.show-thread-link, a.ThreadedConversation-moreRepliesLink {
color: inherit !important;
}
.fullname,
.stream-item a:hover .fullname,
.stream-item a:active .fullname
{color:inherit;}
`;
document.head.appendChild(style);
2018-12-16 17:36:19 +01:00
} else if (hostname == 'reddit.com') {
2018-11-16 21:51:31 +01:00
var style = document.createElement('style');
style.textContent = `
.author { color: #369 !important;}
`;
document.head.appendChild(style);
}
2018-10-30 18:10:57 +01:00
}
2018-12-16 17:36:19 +01:00
function maybeDisableCustomCss() {
2018-11-16 21:51:31 +01:00
var shouldDisable = null;
2018-12-16 17:36:19 +01:00
if (hostname == 'twitter.com') shouldDisable = x => x.ownerNode && x.ownerNode.id && x.ownerNode.id.startsWith('user-style');
else if (hostname == 'medium.com') shouldDisable = x => x.ownerNode && x.ownerNode.className && x.ownerNode.className == 'js-collectionStyle';
else if (hostname == 'disqus.com') shouldDisable = x => x.ownerNode && x.ownerNode.id && x.ownerNode.id.startsWith('css_');
2018-09-16 12:27:42 +02:00
2018-12-16 17:36:19 +01:00
if (shouldDisable)
2018-11-16 21:51:31 +01:00
[...document.styleSheets].filter(shouldDisable).forEach(x => x.disabled = true);
}
2018-09-16 12:27:42 +02:00
function init() {
2018-11-16 21:51:31 +01:00
fixupSiteStyles();
2018-12-16 17:36:19 +01:00
2018-11-16 21:51:31 +01:00
if (isHostedOn(hostname, 'youtube.com')) {
setInterval(updateYouTubeChannelHeader, 300);
setInterval(updateAllLabels, 6000);
2018-11-16 21:51:31 +01:00
}
if (myself && (myself.href || myself.startsWith('http:') || myself.startsWith('https:')))
myself = getIdentifier(myself);
2018-12-16 16:54:01 +01:00
console.log('Self: ' + myself)
2018-11-16 21:51:31 +01:00
maybeDisableCustomCss();
2018-09-16 12:27:42 +02:00
updateAllLabels();
2018-12-16 17:36:19 +01:00
2018-09-16 12:27:42 +02:00
var observer = new MutationObserver(mutationsList => {
2018-11-16 21:51:31 +01:00
maybeDisableCustomCss();
2018-09-16 12:27:42 +02:00
for (var mutation of mutationsList) {
if (mutation.type == 'childList') {
for (var node of mutation.addedNodes) {
if (node.tagName == 'A') {
initLink(node);
}
if (node.querySelectorAll) {
for (var subnode of node.querySelectorAll('a')) {
initLink(subnode);
}
}
}
}
}
solvePendingLabels();
});
observer.observe(document.body, {
childList: true,
subtree: true
});
document.addEventListener('contextmenu', evt => {
lastRightClickedElement = evt.target;
}, true);
2018-09-16 12:27:42 +02:00
}
var lastRightClickedElement = null;
2018-10-30 18:10:57 +01:00
var lastAppliedYouTubeUrl = null;
var lastAppliedYouTubeTitle = null;
2018-12-16 17:36:19 +01:00
function updateYouTubeChannelHeader() {
2018-10-30 18:10:57 +01:00
var url = window.location.href;
var title = document.getElementById('channel-title');
2018-12-16 17:36:19 +01:00
if (title && title.tagName == 'H3') title = null; // search results, already a link
2018-10-30 18:10:57 +01:00
var currentTitle = title ? title.textContent : null;
2018-12-16 17:36:19 +01:00
if (url == lastAppliedYouTubeUrl && currentTitle == lastAppliedYouTubeTitle) return;
2018-10-30 18:10:57 +01:00
lastAppliedYouTubeUrl = url;
lastAppliedYouTubeTitle = currentTitle;
2018-12-16 17:36:19 +01:00
if (currentTitle) {
2018-10-30 18:10:57 +01:00
var replacement = document.getElementById('channel-title-replacement');
2018-12-16 17:36:19 +01:00
if (!replacement) {
2018-10-30 18:10:57 +01:00
replacement = document.createElement('A');
replacement.id = 'channel-title-replacement'
replacement.className = title.className;
title.parentNode.insertBefore(replacement, title.nextSibling);
title.style.display = 'none';
replacement.style.fontSize = '2.4rem';
replacement.style.fontWeight = '400';
replacement.style.lineHeight = '3rem';
replacement.style.textDecoration = 'none';
replacement.style.color = 'black';
2018-10-30 18:10:57 +01:00
}
replacement.textContent = lastAppliedYouTubeTitle;
replacement.href = lastAppliedYouTubeUrl;
}
updateAllLabels();
setTimeout(updateAllLabels, 2000);
setTimeout(updateAllLabels, 4000);
2018-10-30 18:10:57 +01:00
}
2018-09-16 12:27:42 +02:00
function updateAllLabels(refresh) {
if (refresh) knownLabels = {};
var links = document.links;
for (var i = 0; i < links.length; i++) {
var a = links[i];
initLink(a);
}
solvePendingLabels();
}
var knownLabels = {};
var labelsToSolve = [];
function solvePendingLabels() {
if (!labelsToSolve.length) return;
var uniqueIdentifiers = Array.from(new Set(labelsToSolve.map(x => x.identifier)));
var tosolve = labelsToSolve;
labelsToSolve = [];
browser.runtime.sendMessage({ ids: uniqueIdentifiers, myself: myself }, response => {
for (item of tosolve) {
var label = response[item.identifier];
knownLabels[item.identifier] = label || '';
applyLabel(item.element, item.identifier);
}
});
}
function applyLabel(a, identifier) {
if (a.assignedCssLabel) {
a.classList.remove('assigned-label-' + a.assignedCssLabel);
a.classList.remove('has-assigned-label');
}
2018-12-03 22:19:33 +01:00
a.assignedCssLabel = knownLabels[identifier] || '';
2018-09-16 12:27:42 +02:00
if (a.assignedCssLabel) {
a.classList.add('assigned-label-' + a.assignedCssLabel);
a.classList.add('has-assigned-label');
2018-12-03 22:19:54 +01:00
if (hostname == 'twitter.com')
a.classList.remove('u-textInheritColor');
2018-09-16 12:27:42 +02:00
}
}
2018-12-16 17:36:19 +01:00
function initLink(a) {
2018-09-16 12:27:42 +02:00
var identifier = getIdentifier(a);
if (!identifier){
if(hostname == 'youtube.com')
applyLabel(a, '');
return;
}
2018-09-16 12:27:42 +02:00
var label = knownLabels[identifier];
if (label === undefined) {
labelsToSolve.push({ element: a, identifier: identifier });
return;
}
applyLabel(a, identifier);
}
function isHostedOn(/** @type {string}*/fullHost, /** @type {string}*/baseHost) {
if (baseHost.length > fullHost.length) return false;
if (baseHost.length == fullHost.length) return baseHost == fullHost;
var k = fullHost.charCodeAt(fullHost.length - baseHost.length - 1);
if (k == 0x2E) return fullHost.endsWith(baseHost);
else return false;
}
function getQuery(/** @type {string}*/search) {
if (!search) return {};
var s = {};
if (search.startsWith('?')) search = search.substring(1);
for (var pair of search.split('&')) {
var z = pair.split('=');
if (z.length != 2) continue;
s[decodeURIComponent(z[0]).replace(/\+/g, ' ')] = decodeURIComponent(z[1].replace(/\+/g, ' '));
}
return s;
}
function takeFirstPathComponents(/** @type {string}*/path, /** @type {number}*/num) {
var m = path.split('/')
m = m.slice(1, 1 + num);
if (m.length && !m[m.length - 1]) m.length--;
if (m.length != num) return '!!'
2018-09-16 12:27:42 +02:00
return '/' + m.join('/');
}
2018-12-16 11:32:37 +01:00
function takeNthPathComponent(/** @type {string}*/path, /** @type {number}*/nth) {
return path.split('/')[nth + 1] || null;
}
2018-09-16 12:27:42 +02:00
2018-12-16 17:36:19 +01:00
function captureRegex(str, regex) {
if (!str) return null;
var match = str.match(regex);
2018-12-16 17:36:19 +01:00
if (match && match[1]) return match[1];
return null;
}
2018-09-16 12:27:42 +02:00
function getCurrentFacebookPageId() {
// page
var elem = document.querySelector("a[rel=theater][aria-label='Profile picture']");
if (elem) {
var p = captureRegex(elem.href, /facebook\.com\/(\d+)/)
if (p) return p;
2018-09-16 12:27:42 +02:00
}
// page (does not work if page is loaded directly)
elem = document.querySelector("[ajaxify^='/page_likers_and_visitors_dialog']")
if (elem) return captureRegex(elem.getAttribute('ajaxify'), /\/(\d+)\//);
2018-09-16 12:27:42 +02:00
// group
elem = document.querySelector("[id^='headerAction_']");
if (elem) return captureRegex(elem.id, /_(\d+)/);
2018-09-16 12:27:42 +02:00
// profile
elem = document.querySelector('#pagelet_timeline_main_column');
if (elem && elem.dataset.gt) return JSON.parse(elem.dataset.gt).profile_owner;
return null;
}
function getIdentifier(urlstr) {
2018-12-16 17:36:19 +01:00
try {
var k = getIdentifierInternal(urlstr);
2019-02-08 20:43:06 +01:00
if (!k || k.indexOf('!') != -1) return null;
2019-01-14 23:11:06 +01:00
return k.toLowerCase();
2018-12-16 17:36:19 +01:00
} catch (e) {
2018-12-16 11:32:37 +01:00
console.warn("Unable to get identifier for " + urlstr);
return null;
}
}
function getIdentifierInternal(urlstr) {
2018-09-16 12:27:42 +02:00
if (!urlstr) return null;
if (hostname == 'reddit.com') {
var parent = urlstr.parentElement;
if (parent && parent.classList.contains('domain') && urlstr.textContent.startsWith('self.')) return null;
}
if (hostname == 'disqus.com') {
if (urlstr.classList && urlstr.classList.contains('time-ago')) return null;
}
if (hostname == 'facebook.com' && urlstr.tagName) {
2018-09-16 12:27:42 +02:00
var parent = urlstr.parentElement;
if (parent && (parent.tagName == 'H1' || parent.id == 'fb-timeline-cover-name')) {
var id = getCurrentFacebookPageId();
//console.log('Current fb page: ' + id)
if (id)
return 'facebook.com/' + id;
}
// comment timestamp
if (urlstr.firstChild && urlstr.firstChild.tagName == 'ABBR' && urlstr.lastChild == urlstr.firstChild) return null;
// post 'see more'
if (urlstr.classList.contains('see_more_link')) return null;
// post 'continue reading'
if (parent && parent.classList.contains('text_exposed_link')) return null;
2018-09-16 12:27:42 +02:00
if (urlstr.dataset) {
var hovercard = urlstr.dataset.hovercard;
if (hovercard) {
var id = captureRegex(hovercard, /id=(\d+)/);
2018-09-16 12:27:42 +02:00
if (id)
return 'facebook.com/' + id;
}
// post Comments link
if (urlstr.dataset.testid == 'UFI2CommentsCount/root') return null;
// post Comments link
if (urlstr.dataset.commentPreludeRef) return null;
// page left sidebar
if (urlstr.dataset.endpoint) return null;
2019-03-03 21:02:57 +01:00
// profile tabs
if (urlstr.dataset.tabKey) return null;
2018-09-16 12:27:42 +02:00
var gt = urlstr.dataset.gt;
if (gt) {
var gtParsed = JSON.parse(gt);
if (gtParsed.engagement && gtParsed.engagement.eng_tid) {
return 'facebook.com/' + gtParsed.engagement.eng_tid;
}
}
// comment interaction buttons
if (urlstr.dataset.sigil) return null;
2018-09-16 12:27:42 +02:00
var p = urlstr;
while (p) {
var bt = p.dataset.bt;
if (bt) {
var btParsed = JSON.parse(bt);
if (btParsed.id) return 'facebook.com/' + btParsed.id;
}
p = p.parentElement;
}
}
}
2018-12-16 15:30:26 +01:00
if (urlstr.dataset && urlstr.dataset.expandedUrl) urlstr = urlstr.dataset.expandedUrl;
2018-09-16 12:27:42 +02:00
if (urlstr.href !== undefined) urlstr = urlstr.href;
if (!urlstr) return null;
if (urlstr.endsWith('#')) return null;
try {
var url = new URL(urlstr);
} catch (e) {
return null;
}
if (url.protocol != 'http:' && url.protocol != 'https:') return null;
// fb group member badge
if (url.pathname.includes('/badge_member_list/')) return null;
2018-09-16 12:27:42 +02:00
if (url.href.indexOf('http', 1) != -1) {
var s = getQuery(url.search);
urlstr = null;
for (var key in s) {
if (s.hasOwnProperty(key)) {
var element = s[key];
if (element.startsWith('http:') || element.startsWith('https')) {
urlstr = element;
break;
}
}
}
if (urlstr == null) {
urlstr = url.href.substring(url.href.indexOf('http', 1))
}
try {
url = new URL(urlstr);
} catch (e) { }
}
var host = url.hostname;
if (isHostedOn(host, 'web.archive.org')) {
var match = captureRegex(url.href, /\/web\/\w+\/(.*)/);
2018-09-16 12:27:42 +02:00
if (!match) return null;
2018-12-16 11:32:37 +01:00
return getIdentifierInternal('http://' + match);
2018-09-16 12:27:42 +02:00
}
2018-12-16 17:36:19 +01:00
if (url.search && url.search.includes('http')) {
if (url.pathname.startsWith('/intl/')) return null; // facebook language switch links
2018-12-16 17:36:19 +01:00
for (var q of url.searchParams) {
if (q[1].startsWith('http')) return getIdentifierInternal(q[1]);
2018-12-16 11:32:37 +01:00
}
}
/*
if(host == 't.umblr.com'){
return getIdentifierInternal(url.searchParams.get('z'));
}
*/
2018-09-16 12:27:42 +02:00
if (host.startsWith('www.')) host = host.substring(4);
if (isHostedOn(host, 'facebook.com')) {
var s = getQuery(url.search);
var p = url.pathname.replace('/pg/', '/');
2019-02-25 23:44:34 +01:00
return 'facebook.com/' + (s.id || takeFirstPathComponents(p, p.startsWith('/groups/') ? 2 : 1).substring(1));
2018-09-16 12:27:42 +02:00
}
if (isHostedOn(host, 'reddit.com')) {
var pathname = url.pathname.replace('/u/', '/user/');
if (!pathname.startsWith('/user/') && !pathname.startsWith('/r/')) return null;
if(pathname.includes('/comments/') && hostname == 'reddit.com') return null;
2019-01-14 23:11:06 +01:00
return 'reddit.com' + takeFirstPathComponents(pathname, 2);
2018-09-16 12:27:42 +02:00
}
if (isHostedOn(host, 'twitter.com')) {
2019-01-14 23:11:06 +01:00
return 'twitter.com' + takeFirstPathComponents(url.pathname, 1);
2018-09-16 12:27:42 +02:00
}
if (isHostedOn(host, 'youtube.com')) {
2019-04-08 16:26:09 +02:00
var pathname = url.pathname.replace('/c/', '/user/');
if (!pathname.startsWith('/user/') && !pathname.startsWith('/channel/')) return null;
2019-04-08 16:26:09 +02:00
return 'youtube.com' + takeFirstPathComponents(pathname, 2);
2018-09-16 12:27:42 +02:00
}
2018-11-16 21:51:31 +01:00
if (isHostedOn(host, 'disqus.com') && url.pathname.startsWith('/by/')) {
return 'disqus.com' + takeFirstPathComponents(url.pathname, 2);
}
if (isHostedOn(host, 'medium.com')) {
2019-06-14 18:51:22 +02:00
return 'medium.com' + takeFirstPathComponents(url.pathname.replace('/t/', '/'), 1);
2018-11-16 21:51:31 +01:00
}
2018-12-16 11:32:37 +01:00
if (isHostedOn(host, 'tumblr.com')) {
2018-12-16 17:36:19 +01:00
if (url.pathname.startsWith('/register/follow/')) {
2018-12-16 11:32:37 +01:00
var name = takeNthPathComponent(url.pathname, 2);
return name ? name + '.tumblr.com' : null;
}
2018-12-16 17:36:19 +01:00
if (host != 'www.tumblr.com' && host != 'assets.tumblr.com' && host.indexOf('.media.') == -1) {
2019-01-14 23:11:06 +01:00
if (!url.pathname.startsWith('/tagged/')) return url.host;
2018-12-16 11:32:37 +01:00
}
return null;
}
2019-01-13 17:16:37 +01:00
if (isHostedOn(host, 'wikipedia.org') || isHostedOn(host, 'rationalwiki.org')) {
if (url.hash || url.pathname.includes(':')) return null;
2019-01-13 17:16:37 +01:00
if (url.pathname.startsWith('/wiki/')) return 'wikipedia.org' + takeFirstPathComponents(url.pathname, 2);
else return null;
}
2018-09-16 12:27:42 +02:00
if (host.indexOf('.blogspot.') != -1) {
var m = captureRegex(host, /([a-zA-Z0-9\-]*)\.blogspot/);
2019-01-14 23:11:06 +01:00
if (m) return m + '.blogspot.com';
2018-09-16 12:27:42 +02:00
}
var id = host;
if (id.startsWith('www.')) id = id.substr(4);
if (id.startsWith('m.')) id = id.substr(2);
2019-01-14 23:11:06 +01:00
return id;
2018-09-16 12:27:42 +02:00
}
init();
2018-12-17 21:56:30 +01:00
var lastGeneratedLinkId = 0;
function getSnippet(node){
2019-03-03 21:02:57 +01:00
while (node) {
var classList = node.classList;
if (hostname == 'facebook.com' && node.dataset && node.dataset.ftr) return node;
if (hostname == 'reddit.com' && (classList.contains('scrollerItem') || classList.contains('thing') || classList.contains('Comment'))) return node;
if (hostname == 'twitter.com' && (classList.contains('stream-item'))) return node;
if (hostname == 'disqus.com' && (classList.contains('post-content'))) return node;
if (hostname == 'medium.com' && (classList.contains('streamItem') || classList.contains('streamItemConversationItem'))) return node;
if (hostname == 'youtube.com' && node.tagName == 'YTD-COMMENT-RENDERER') return node;
if (hostname.endsWith('tumblr.com') && (node.dataset.postId || classList.contains('post'))) return node;
node = node.parentElement;
}
return null;
}
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.updateAllLabels) {
updateAllLabels(true);
return;
}
message.contextPage = window.location.href;
var target = lastRightClickedElement; // message.elementId ? browser.menus.getTargetElement(message.elementId) : null;
while(target){
if(target.href) break;
target = target.parentElement;
}
if (target && target.href != message.url) target = null;
var identifier = target ? getIdentifier(target) : getIdentifier(message.url);
if (!identifier) return;
message.identifier = identifier;
if (identifier.startsWith('facebook.com/'))
message.secondaryIdentifier = getIdentifier(message.url);
2019-03-03 21:02:57 +01:00
var snippet = getSnippet(target);
2018-12-17 21:56:30 +01:00
message.linkId = ++lastGeneratedLinkId;
if (target)
target.setAttribute('shinigami-eyes-link-id', lastGeneratedLinkId);
2018-12-17 21:56:30 +01:00
message.snippet = snippet ? snippet.outerHTML : null;
2018-12-16 17:36:19 +01:00
var debugClass = 'shinigami-eyes-debug-snippet-highlight';
2018-12-17 21:56:30 +01:00
if (snippet && message.debug) {
snippet.classList.add(debugClass);
2018-12-16 17:36:19 +01:00
if (message.debug <= 1)
setTimeout(() => snippet.classList.remove(debugClass), 1500)
2018-12-16 17:36:19 +01:00
}
2018-09-16 12:27:42 +02:00
sendResponse(message);
})