-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
79 lines (70 loc) · 1.81 KB
/
background.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
69
70
71
72
73
74
75
76
77
78
79
'use strict';
function getLocation(href) {
var match = href.match(/^(https?:)\/\/(([^:/?#]*)(?::([0-9]+))?)(\/[^?#]*)(\?[^#]*|)(#.*|)$/);
return match && {
protocol: match[1],
host: match[2],
hostname: match[3],
port: match[4],
pathname: match[5],
search: match[6],
hash: match[7]
};
}
function popSubdomain(str) {
var newName = str.replace(/[^.]*\./, '');
return str !== newName && newName;
}
function insertCSS(tabId, hostname) {
if (!hostname) {
return;
}
chrome.tabs.insertCSS(tabId, {
file: 'JsCssExtender/' + hostname + '.css',
runAt: 'document_start',
allFrames: true
}, function (res) {
if (chrome.runtime.lastError) {
// fail silently
return;
}
});
// attempt to insert next stylesheet in a subdomain chain
insertCSS(tabId, popSubdomain(hostname));
}
function executeScript(tabId, hostname) {
if (!hostname) {
return;
}
chrome.tabs.executeScript(tabId, {
file: 'JsCssExtender/' + hostname + '.js'
}, function(res) {
if (chrome.runtime.lastError) {
// fail silently
return;
}
});
// attempt to execute next script in a subdomain chain
executeScript(tabId, popSubdomain(hostname));
}
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
var match = getLocation(tab.url);
// load css early for no visible delays
if (changeInfo.status === 'loading') {
// attempt to insert default css
insertCSS(tabId, 'default');
if (match) {
// attempt to insert domain specific css
insertCSS(tabId, match.hostname);
}
}
// load js
if (changeInfo.status === 'complete') {
// attempt to execute default js
executeScript(tabId, 'default');
if (match) {
// attempt to insert domain specific css
executeScript(tabId, match.hostname);
}
}
});