-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
50 lines (44 loc) · 1.44 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
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
const text = request.text;
let targetUrl;
const processedUrl = processUrl(text);
if (processedUrl) {
targetUrl = processedUrl;
} else {
const searchText = encodeURIComponent(text);
chrome.storage.sync.get(['searchEngine'], function(result) {
let searchEngineUrl = result.searchEngine || 'https://www.google.com/search?q=%s';
if (searchEngineUrl.includes('%s')) {
targetUrl = searchEngineUrl.replace('%s', searchText);
} else {
targetUrl = "https://www.google.com/search?q=%25s+is+not+in+the+search+engine+URL";
}
createTabNextToActive(targetUrl, request.ctrlKey);
});
}
});
function processUrl(url) {
const invalidChars = /[^a-zA-Z0-9-._~:/?#[\]@!$&'()*+,;=]/;
if (invalidChars.test(url)) {
return null;
}
try {
new URL(url);
return url;
} catch (e) {
const domainRegex = /^([a-zA-Z0-9-]{1,63}\.)+[a-zA-Z]{2,10}$/;
if (domainRegex.test(url)) {
return `https://${url}`;
}
return null;
}
}
function createTabNextToActive(url, ctrlKey) {
chrome.storage.sync.get({newTabActive: true}, function(data) {
let shouldBeActive = data.newTabActive ? !ctrlKey : ctrlKey;
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
const activeTab = tabs[0];
chrome.tabs.create({url: url, index: activeTab.index + 1, active: shouldBeActive});
});
});
}