-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
82 lines (66 loc) · 1.92 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
var currentTab;
var currentURL;
var isDCK; // is the current page a duckduckgo.com page?
// switch to the google url
function switchURL() {
if (isDCK) {
var searchTerm;
var splitted = currentURL.split(/(\?|\&)/);
for (var i = 0; i < splitted.length; i++) {
if (splitted[i].match(/^q=.*$/)) {
searchTerm = splitted[i];
}
}
var google_url = "https://google.com/search?" + searchTerm;
browser.tabs.update({url: google_url});
} else {
console.log('Error: Not a duckduckgo.com site');
}
}
// call switchURL when button is pressed
browser.browserAction.onClicked.addListener(switchURL);
// call switchURL when key command is used
browser.commands.onCommand.addListener(function(command) {
if (command == "switchWithKeypress") {
switchURL();
}
});
// check if switching is possible
function updateDCK() {
var pattern = /^(http|https):\/\/duckduckgo\.com\/[^\s]*(\?|\&)q=.{1,}$/;
isDCK = pattern.test(currentURL);
}
// update the icon to show weather switching is possible
function updateIcon() {
browser.browserAction.setIcon({
path: isDCK ? {
48: "icons/switch_true.svg",
92: "icons/switch_true.svg"
} : {
48: "icons/switch_false.svg",
92: "icons/switch_false.svg"
},
tabId: currentTab.id
});
}
// update everything for the current tab
function updateActiveTab(tabs) {
function updateTab(tabs) {
if (tabs[0]) {
currentTab = tabs[0];
currentURL = tabs[0].url;
updateDCK();
updateIcon();
}
}
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then(updateTab);
}
// listen to tab URL changes
browser.tabs.onUpdated.addListener(updateActiveTab);
// listen to tab switching
browser.tabs.onActivated.addListener(updateActiveTab);
// listen for window switching
browser.windows.onFocusChanged.addListener(updateActiveTab);
// update when the extension loads initially
updateActiveTab();