forked from reservedwords/NewsHacker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
68 lines (57 loc) · 2.03 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
function findThread(targetUrl, callbacks) {
function handleResponse(response) {
if (!response || !response.hits || response.hits.length === 0) {
callbacks.noThread();
return;
}
if (response.hits.length === 1) {
callbacks.oneThread(response.hits[0]);
return;
}
const exactMatch = response.hits.find(hit => hit.url === targetUrl);
if(exactMatch) {
callbacks.oneThread(exactMatch);
}
else
{
callbacks.multipleThreads(response.hits)
}
}
const targetUrlWithoutScheme = targetUrl.replace(new RegExp('[^:]+://'), '');
const searchUrl = `http://hn.algolia.com/api/v1/search?restrictSearchableAttributes=url&query=${targetUrlWithoutScheme}`;
fetch(searchUrl)
.then(r => r.json())
.then(handleResponse)
.catch(e => callbacks.error(JSON.stringify(e)));
}
function findThreadForActiveTab(callbacks) {
chrome.tabs.query({active: true, currentWindow: true}, arrayOfTabs => {
if(!arrayOfTabs || arrayOfTabs.length === 0) {
callbacks.error('Cannot detect active tab when devtools is in focus');
}
const activeTab = arrayOfTabs[0];
findThread(activeTab.url, callbacks)
});
}
function openThreadInNewTab(hit) {
const hnThread = `https://news.ycombinator.com/item?id=${hit.objectID}`;
chrome.tabs.create({url: hnThread})
}
function postEmptyThreadMessage(port){
return hits => port.postMessage({ success: true, threads: []});
}
function postThreadMessage(port) {
return hits => port.postMessage({ success: true, threads: hits});
}
function postError(port) {
return err => port.postMessage({success: false, error: err});
}
chrome.extension.onConnect.addListener(port => {
const callbacks = {
noThread: postEmptyThreadMessage(port),
oneThread: openThreadInNewTab,
multipleThreads: postThreadMessage(port),
error: postError(port)
};
findThreadForActiveTab(callbacks);
});