-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
93 lines (81 loc) · 2.5 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
let tabs = {};
chrome = this.browser || this.chrome;
const inspectFile = 'inspect.js';
const activeIcon = 'active-64.png';
const defaultIcon = 'default-64.png';
const inspect = {
toggleActivate: function(id, type, icon) {
this.id = id;
chrome.tabs.executeScript(id, {file: inspectFile}, function() {
chrome.tabs.sendMessage(id, {action: type});
}.bind(this));
chrome.browserAction.setIcon({tabId: id, path: {19: 'icons/' + icon}});
}
};
function toggle(tab) {
if (isSupportedProtocol(tab.url)) {
if (!tabs[tab.id]) {
tabs[tab.id] = Object.create(inspect);
inspect.toggleActivate(tab.id, 'activate', activeIcon);
} else {
inspect.toggleActivate(tab.id, 'deactivate', defaultIcon);
for (let tabId in tabs) {
if (tabId == tab.id) delete tabs[tabId];
}
}
}
}
function deactivateItem(tab) {
if (tab[0]) {
if (isSupportedProtocol(tab[0].url)) {
for (let tabId in tabs) {
if (tabId == tab[0].id) {
delete tabs[tabId];
inspect.toggleActivate(tab[0].id, 'deactivate', defaultIcon);
}
}
}
}
}
function getActiveTab() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
deactivateItem(tabs);
});
}
function isSupportedProtocol(urlString) {
const supportedProtocols = ['https:', 'http:', 'file:'];
const url = document.createElement('a');
url.href = urlString;
return supportedProtocols.indexOf(url.protocol) != -1;
}
chrome.commands.onCommand.addListener(command => {
if (command === 'toggle-xpath') {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
toggle(tabs[0]);
});
}
});
chrome.extension.onConnect.addListener(function(port) {
console.assert(port.name == 'screenshot');
port.onMessage.addListener(function(msg) {
if (msg.request == 'screenshot') {
chrome.tabs.captureVisibleTab(
null, {format: 'jpeg', quality: 100}, function(img) {
// post message only after call back return with Data URL
port.postMessage(img);
});
}
});
});
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log(request);
if (request.contentScriptQuery == 'sendAnnotations') {
var url = 'http://localhost:8000';
fetch(url, {method: 'post', body: request.body}).then(function(response) {
return response.text();
});
return true;
}
});
chrome.tabs.onUpdated.addListener(getActiveTab);
chrome.browserAction.onClicked.addListener(toggle);