forked from JeffreyATW/mbfc_icon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getTabSource.js
68 lines (63 loc) · 1.98 KB
/
getTabSource.js
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
var getHostName = function (url) {
try {
return new URL(url).hostname.match(/(www[0-9]?\.)?(.+)/i)[2];
} catch (e) {
return null; // Invalid URL
}
}
var getPath = function (url) {
try {
return new URL(url).pathname;
} catch (e) {
return '/';
}
}
var getTabSource = function (url, cb) {
browser.storage.local.get(['biases', 'sources'], function (items) {
var hostName = getHostName(url);
var path = getPath(url);
var domainSources;
var source;
var getDomainSource = function (domain) {
domainSources = items.sources[domain];
// check if value is an array or object
if (domainSources) {
if (domainSources.length) {
for (var i = 0; i < domainSources.length; i += 1) {
// if source hasn't been set, settle for root path
if (domainSources[i].path === '/' && source === undefined) {
source = domainSources[i];
} else {
// check for source's path at beginning of current path
if (path.indexOf(domainSources[i].path) === 0) {
source = domainSources[i];
// we found it, no need to iterate further
break;
}
}
}
/* note: source could still be undefined if no domain source paths
were found in current path */
} else {
// not an array, must be slurping old JSON
source = domainSources;
}
} else {
// see if current domain is actually subdomain and look for source of
// parent
const upDomainLevel = domain.match(/[^\.]+\.([^\.]+\..+)/);
if (upDomainLevel) {
return getDomainSource(upDomainLevel[1]);
}
}
return source;
}
if (items.biases !== undefined && items.sources !== undefined) {
source = getDomainSource(hostName);
if (source !== undefined) {
var bias = items.biases[source.bias];
}
}
cb(source, bias);
});
};