-
Notifications
You must be signed in to change notification settings - Fork 31
/
background.js
104 lines (82 loc) · 2.52 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'use strict';
chrome.runtime.onMessage.addListener(function (req, sender, sendResponse) {
var handler = {
/**
* Get active tab
*
* @returns {boolean}
*/
getActiveTab: function () {
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
sendResponse(tabs[0]);
});
return true;
},
/**
* Get active tab
*
* @returns {boolean}
*/
getStorage: function (params) {
chrome.storage.sync.get(params.keys, function (items) {
sendResponse(items);
});
return true;
},
};
return handler[req.type](req.params);
});
chrome.browserAction.onClicked.addListener(function (tab) {
// @todo open the like on github window
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (changeInfo.status !== 'loading')
return;
// Inject the required assets
chrome.tabs.executeScript(tabId, {
code: 'var injected = window.likeOnGithubInjected; window.likeOnGithubInjected = true; injected;',
runAt: 'document_start'
}, function (res) {
if (chrome.runtime.lastError || // don't continue if error
res[0]) // value of `injected` above: don't inject twice
return;
var cssFiles = [
'assets/css/inject.css'
],
jsFiles = [
'assets/lib/jquery.js',
'assets/lib/keymaster.js',
'like-on-github.js'
];
eachTask([function (cb) {
return eachItem(cssFiles, inject('insertCSS'), cb);
}, function (cb) {
return eachItem(jsFiles, inject('executeScript'), cb);
}]);
function inject(fn) {
return function (file, cb) {
chrome.tabs[fn](tabId, {file: file, runAt: 'document_start'}, cb);
};
}
});
});
function eachTask(tasks, done) {
(function next() {
var index = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
if (index === tasks.length) {
done && done();
} else {
tasks[index](function () {
return next(++index);
});
}
})();
}
function eachItem(arr, iter, done) {
var tasks = arr.map(function (item) {
return function (cb) {
return iter(item, cb);
};
});
return eachTask(tasks, done);
}