-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
82 lines (68 loc) · 2.77 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
function titleCase(str) {
str = str.toLowerCase().split(' ')
for (var i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1)
}
return str.join(' ')
}
function getJournalProp(head, query) {
// shakes fist at javascript
const prop = head.querySelector(`meta[name='citation_${query}']`)
|| head.querySelector(`meta[name='dc.${query}']`)
|| head.querySelector(`meta[name='dc.${titleCase(query)}']`)
|| head.querySelector(`meta[name='dc.publisher']`)
if (!prop) return
return prop.content
}
const getArticleProps = url => {
return new Promise((resolve, reject) => {
const method = 'GET';
const citeProps = ['title']
const metaProps = {url: url}
const xhr = new XMLHttpRequest()
xhr.open(method, url)
xhr.responseType = "document"
xhr.onload = function() {
const headElt = this.responseXML && this.responseXML.head
if (!headElt) resolve() // no response, nothing to do
// get journal title, requires a few checks
metaProps['journal_title'] = headElt.querySelector(`meta[name='citation_journal_title']`) ||
headElt.querySelector(`meta[name='dc.source']`) ||
headElt.querySelector(`meta[name='dc.Source']`) ||
headElt.querySelector(`meta[name='dc.publisher']`)
if (!metaProps['journal_title']) {
// TODO: better deal with horrible DOI javascript redirects
const redirectURL = this.responseXML.body.querySelector('[name="redirectURL"]')
const nextURL = redirectURL && redirectURL.value !== null && decodeURIComponent(redirectURL.value)
if (!nextURL) return resolve(); // no further URL to search
console.warn('No journal! Trying with', nextURL)
console.warn(this.responseXML)
xhr.open(method, decodeURIComponent(nextURL))
return xhr.send()
}
metaProps['journal_title'] = metaProps['journal_title'].content
// get other props
citeProps.forEach((prop) => metaProps[prop] = getJournalProp(headElt, prop))
console.log('Found properties', metaProps)
resolve(metaProps)
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send()
});
}
function getAllArticleData(articleDataProms, cb) {
return Promise.all(articleDataProms).then(articleData => {
cb(articleData.filter(data => data != null))
}).catch(err => console.error(err))
}
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
const { urls } = request;
const articleDataProms = urls.map(url => getArticleProps(url))
getAllArticleData(articleDataProms, callback)
return true; // async
})