aboutsummaryrefslogtreecommitdiffstats
path: root/background.js
blob: 558fb5575fab3d0e4290d8c2dd96080c7cf495d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright (c) 2018, 2021  Teddy Wing
//
// This file is part of Legibility.
//
// Legibility is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at
// your option) any later version.
//
// Legibility is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Legibility. If not, see <https://www.gnu.org/licenses/>.

var browser;

if (chrome) {
	browser = chrome;
}

browser.runtime.onMessage.addListener(function(message) {
	browser.webNavigation.onCompleted.addListener(function(details) {
		var url = new URL(details.url);

		if (url.hostname === message.domain) {
			wildcard_domains(message.domain)
				.forEach(function(domain) {
					browser.tabs.insertCSS(
						details.tabId,
						{ file: '/css/' + domain + '.css' }
					);
				});
		}
	});
});


// Build a list of wildcard domains from the given hostname.
//
// Example:
//
//     wildcard_domains('en.wikipedia.org');
//     => [ '%', '%.org', '%.wikipedia.org', 'en.wikipedia.org' ]
function wildcard_domains (hostname) {
	var domain_parts = hostname.split('.');
	var domains = [];

	for (var i = domain_parts.length - 1; i >= 0; i--) {
		var domain;

		if (domains[domains.length - 1]) {
			domain = domain_parts[i] + '.' + domains[domains.length - 1];
		}
		else {
			domain = domain_parts[i];
		}

		domains.push(domain);
	}

	for (var i = 0; i < domains.length - 1; i++) {
		domains[i] = '%.' + domains[i];
	}

	domains.unshift('%');

	return domains;
}


// Keyboard shortcuts.
browser.commands.onCommand.addListener(function(command) {
	if (command === 'reload') {
		browser.runtime.reload();
	}
});