-
Notifications
You must be signed in to change notification settings - Fork 83
/
extension-background.js
72 lines (61 loc) · 1.87 KB
/
extension-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
const WebExtension = (typeof browser !== 'undefined') ? browser : chrome;
var C = {
'tabIds': [],
'WebID': null
};
function injectResources(tabId, files) {
var getFileExtension = /(?:\.([^.]+))?$/;
//helper function that returns appropriate chrome.tabs function to load resource
var loadFunctionForExtension = (ext) => {
switch(ext) {
case 'js' : return WebExtension.tabs.executeScript;
case 'css' : return WebExtension.tabs.insertCSS;
default: throw new Error('Unsupported resource type')
}
};
return Promise.all(files.map(resource => new Promise((resolve, reject) => {
var ext = getFileExtension.exec(resource)[1];
var loadFunction = loadFunctionForExtension(ext);
// loadFunction(C.tabId, {file: resource}).then(() => {
loadFunction(tabId, {file: resource}, () => {
if (WebExtension.runtime.lastError) {
reject(WebExtension.runtime.lastError);
}
else {
resolve();
}
});
})));
}
function dokieliInit(tab) {
// console.log(tab);
injectResources(tab.id, ["media/css/dokieli.css"]).then(() => {
}).catch(err => {
// console.log('Error occurred: '+err);
});
}
function showDocumentMenu(tab) {
WebExtension.tabs.sendMessage(tab.id, {action: "dokieli.showDocumentMenu", webid: C.WebID}, function(r){
if(C.tabIds.indexOf(tab.id) < 0) {
C.tabIds.push(tab.id);
}
});
}
WebExtension.browserAction.onClicked.addListener(function(tab){
WebExtension.tabs.sendMessage(tab.id, {action: "dokieli.status"},
function(response) {
if (response && !response.dokieli) {
dokieliInit(tab);
}
showDocumentMenu(tab);
});
});
WebExtension.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.property == "webid" && C.WebID) {
sendResponse({ "webid": C.WebID });
}
else {
sendResponse({});
}
return true;
});