Skip to content

Commit bc6deb4

Browse files
committed
rework background js stuff and manifest
1 parent f2fcacb commit bc6deb4

File tree

4 files changed

+147
-248
lines changed

4 files changed

+147
-248
lines changed

background.js

+85-166
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,44 @@
1-
/*
2-
Initialize
3-
*/
4-
Zotero.Debug.init(1)
5-
// Zotero.Repo.init()
6-
Zotero.Messaging.init()
7-
Zotero.Connector_Types.init()
8-
Zotero.Translators.init()
9-
zsc.init()
10-
//wsClient.startClient(); // TODO: don't start websocket client, until JabRef's counterpart is integrated
11-
12-
this.tabInfo = new Map()
13-
14-
/*
15-
Show/hide import button for all tabs (when add-on is loaded).
16-
*/
17-
browser.tabs.query({}).then((tabs) => {
18-
// We wait a bit before injection to give Zotero time to load the translators
19-
setTimeout(() => {
20-
console.log('JabRef: Inject into open tabs %o', tabs)
21-
for (let tab of tabs) {
22-
installInTab(tab)
1+
const isFirefox = typeof browser !== 'undefined';
2+
const browserAPI = isFirefox ? browser : chrome;
3+
const actionAPI = isFirefox ? browserAPI.pageAction : browserAPI.action;
4+
5+
// Initialize the translator framework
6+
init = async function() {
7+
Zotero.Debug.init(1);
8+
await Zotero.Connector_Browser.init();
9+
await Zotero.Messaging.init();
10+
await Zotero.Translators.init();
11+
zsc.init();
12+
13+
this.tabInfo = new Map();
14+
15+
// Register message listeners
16+
Zotero.Messaging.addMessageListener('Connector_Browser.onTranslators', onTranslators);
17+
browserAPI.tabs.onUpdated.addListener(onTabUpdated);
18+
browserAPI.tabs.onRemoved.addListener(Zotero.Connector_Browser.onPageLoad);
19+
20+
// Initialize existing tabs
21+
const tabs = await browserAPI.tabs.query({});
22+
for (let tab of tabs) {
23+
if (!isDisabledForURL(tab.url)) {
24+
await installInTab(tab);
2325
}
24-
}, 1500)
25-
})
26-
27-
/*
28-
Show/hide import button for the currently active tab, whenever the user navigates.
29-
*/
30-
browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
31-
if (!changeInfo.url) {
32-
return
3326
}
34-
browser.tabs
35-
.query({
36-
active: true,
37-
currentWindow: true,
38-
})
39-
.then((tabs) => {
40-
if (tabId === tabs[0].id) {
41-
var tab = tabs[0]
42-
43-
// Clear old translator information
44-
Zotero.Connector_Browser.onPageLoad(tab)
45-
46-
installInTab(tab)
47-
}
48-
})
49-
})
27+
}
5028

51-
/*
52-
Remove translator information when tab is closed.
53-
*/
54-
browser.tabs.onRemoved.addListener(Zotero.Connector_Browser.onPageLoad)
29+
function onTabUpdated(tabId, changeInfo, tab) {
30+
if (!changeInfo.url) return;
31+
32+
browserAPI.tabs.query({
33+
active: true,
34+
currentWindow: true
35+
}).then(tabs => {
36+
if (tabId === tabs[0].id) {
37+
Zotero.Connector_Browser.onPageLoad(tab);
38+
installInTab(tab);
39+
}
40+
});
41+
}
5542

5643
/*
5744
Disable add-on for special browser pages
@@ -64,64 +51,43 @@ function isDisabledForURL(url) {
6451
)
6552
}
6653

67-
/*
68-
Searches for translators for the given tab and shows/hides the import button accordingly.
69-
*/
70-
function installInTab(tab) {
71-
if (isDisabledForURL(tab.url)) {
72-
return
54+
async function installInTab(tab) {
55+
if (isDisabledForURL(tab.url)) return;
56+
57+
tabInfo.delete(tab.id);
58+
59+
try {
60+
await browserAPI.tabs.executeScript(tab.id, { code: 'document.contentType' });
61+
await lookForTranslators(tab);
62+
tabInfo.set(tab.id, { isPDF: false });
63+
} catch (error) {
64+
console.debug(`JabRef: PDF detection - ${error}`);
65+
actionAPI.show(tab.id);
66+
actionAPI.setTitle({
67+
tabId: tab.id,
68+
title: 'Import references into JabRef as PDF'
69+
});
70+
tabInfo.set(tab.id, { isPDF: true });
7371
}
74-
75-
// Reset tab info
76-
tabInfo.delete(tab.id)
77-
78-
// We cannot inject content scripts into PDF: https://bugzilla.mozilla.org/show_bug.cgi?id=1454760
79-
// Thus, our detection algorithm silently fails in this case, as the Inject#init is never called
80-
// Try to detect these situations by calling a content script; this fails
81-
browser.tabs
82-
.executeScript(tab.id, {
83-
code: 'document.contentType',
84-
})
85-
.then((result) => {
86-
lookForTranslators(tab)
87-
tabInfo.set(tab.id, { isPDF: false })
88-
})
89-
.catch((error) => {
90-
console.debug(`JabRef: Error calling content script: ${error}`)
91-
92-
// Assume a PDF is displayed in this tab
93-
browser.pageAction.show(tab.id)
94-
browser.pageAction.setTitle({
95-
tabId: tab.id,
96-
title: 'Import references into JabRef as PDF',
97-
})
98-
tabInfo.set(tab.id, { isPDF: true })
99-
})
10072
}
10173

10274
function lookForTranslators(tab) {
103-
console.log('JabRef: Searching for translators for %o', tab)
104-
Zotero.Translators.getWebTranslatorsForLocation(tab.url, tab.url).then(
75+
console.log('JabRef: Searching for translators for %o', tab);
76+
return Zotero.Translators.getWebTranslatorsForLocation(tab.url, tab.url).then(
10577
(translators) => {
10678
if (translators[0].length === 0) {
107-
// No translators found, so hide button
108-
console.log('JabRef: No translators found')
109-
browser.pageAction.hide(tab.id)
79+
console.log('JabRef: No translators found');
80+
actionAPI.hide(tab.id);
11081
} else {
111-
// Potential translators found, Zotero will check if these can detect something on the website.
112-
// We will be notified about the result of this check using the `onTranslators` method below, so nothing to do here.
113-
console.log(
114-
'JabRef: Found potential translators %o',
115-
translators[0]
116-
)
82+
console.log('JabRef: Found potential translators %o', translators[0]);
11783
}
11884
}
119-
)
85+
);
12086
}
12187

12288
async function evalInTab(tabsId, code) {
12389
try {
124-
result = await browser.tabs.executeScript(tabsId, {
90+
result = await browserAPI.tabs.executeScript(tabsId, {
12591
code: code,
12692
})
12793
console.log(`JabRef: code executed with result ${result}`)
@@ -131,7 +97,6 @@ async function evalInTab(tabsId, code) {
13197
}
13298
}
13399

134-
135100
saveAsWebpage = function (tab) {
136101
var title = tab.title
137102
var url = tab.url
@@ -173,14 +138,14 @@ onTranslators = function (translators, tabId, contentType) {
173138
JSON.parse(JSON.stringify(tabId))
174139
)
175140
tabInfo.set(tabId, { ...tabInfo.get(tabId), hasTranslator: false })
176-
browser.pageAction.setIcon({
141+
actionAPI.setIcon({
177142
tabId: tabId, path: {
178143
"48": "data/JabRef-icon-48.png",
179144
"96": "data/JabRef-icon-96.png"
180145
}
181146
})
182-
browser.pageAction.show(tabId)
183-
browser.pageAction.setTitle({
147+
actionAPI.show(tabId)
148+
actionAPI.setTitle({
184149
tabId: tabId,
185150
title:
186151
'Import simple website reference into JabRef',
@@ -192,85 +157,39 @@ onTranslators = function (translators, tabId, contentType) {
192157
JSON.parse(JSON.stringify(tabId))
193158
)
194159
tabInfo.set(tabId, { ...tabInfo.get(tabId), hasTranslator: true })
195-
browser.pageAction.setIcon({
160+
actionAPI.setIcon({
196161
tabId: tabId, path: {
197162
"48": "data/JabRef-icon-plus-48.png",
198163
"96": "data/JabRef-icon-plus-96.png"
199164
}
200165
})
201-
browser.pageAction.show(tabId)
202-
browser.pageAction.setTitle({
166+
actionAPI.show(tabId)
167+
actionAPI.setTitle({
203168
tabId: tabId,
204169
title:
205170
'Import references into JabRef using ' + translators[0].label,
206171
})
207172
}
208173
}
209174

210-
browser.runtime.onMessage.addListener(function (message, sender, sendResponse) {
175+
browserAPI.runtime.onMessage.addListener((message, sender, sendResponse) => {
211176
if (message.popupOpened) {
212-
// The popup opened, i.e. the user clicked on the page action button
213-
console.log('JabRef: Popup opened confirmed')
214-
215-
browser.tabs
216-
.query({
217-
active: true,
218-
currentWindow: true,
219-
})
220-
.then((tabs) => {
221-
var tab = tabs[0]
222-
var info = tabInfo.get(tab.id)
223-
224-
if (info && info.isPDF) {
225-
console.log(
226-
'JabRef: Export PDF in tab %o',
227-
JSON.parse(JSON.stringify(tab))
228-
)
229-
savePdf(tab)
230-
} else if (info.hasTranslator === false) {
231-
console.log(
232-
'JabRef: No translation, simple saving %o',
233-
JSON.parse(JSON.stringify(tab))
234-
)
235-
saveAsWebpage(tab);
236-
} else {
237-
console.log(
238-
'JabRef: Start translation for tab %o',
239-
JSON.parse(JSON.stringify(tab))
240-
)
241-
Zotero.Connector_Browser.saveWithTranslator(tab, 0)
242-
}
243-
})
177+
handlePopupOpen();
244178
} else if (message.getWsClientState) {
245-
console.debug('JabRef: wsClientState requested')
246-
let wsClientState = {}
247-
wsClientState.clientStarted = wsClient.isClientStarted()
248-
wsClientState.connectionState = wsClient.getConnectionState()
249-
sendResponse(wsClientState)
179+
const wsClientState = {
180+
clientStarted: wsClient.isClientStarted(),
181+
connectionState: wsClient.getConnectionState()
182+
};
183+
sendResponse(wsClientState);
250184
} else if (message.eval) {
251-
console.debug(
252-
'JabRef: eval in background.js: %o',
253-
JSON.parse(JSON.stringify(message.eval))
254-
)
255-
return evalInTab(sender.tab.id, message.eval)
256-
} else if (message[0] === 'Connector_Browser.onTranslators') {
257-
// Intercept message to Zotero background script
258-
console.log(
259-
'JabRef: Intercept message to Zotero background script',
260-
JSON.parse(JSON.stringify(message))
261-
)
262-
message[1][1] = sender.tab.id
263-
onTranslators.apply(null, message[1])
264-
} else if (message[0] === 'Debug.log') {
265-
console.log(message[1])
266-
} else if (message[0] === 'Errors.log') {
267-
console.log(message[1])
268-
} else if (message[0] === 'Prefs.getAll') {
269-
// Ignore, this is handled by Zotero
270-
} else {
271-
console.log(
272-
'JabRef: other message in background.js: %o',
273-
JSON.parse(JSON.stringify(message))
274-
)
185+
return evalInTab(sender.tab.id, message.eval);
186+
} else if (Array.isArray(message) && message[0] === 'Connector_Browser.onTranslators') {
187+
message[1][1] = sender.tab.id;
188+
onTranslators.apply(null, message[1]);
189+
} else if (['Debug.log', 'Errors.log'].includes(message[0])) {
190+
console.log(message[1]);
275191
}
276-
})
192+
});
193+
194+
// Initialize
195+
init();

gulpfile.js

+2
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ gulp.task('copy-external-scripts', async function() {
5555
// './zotero-connectors/src/common/connector.js', // backgroundInclude, we override this in our own connector.js file
5656
'./zotero-connectors/src/common/repo.js', // backgroundInclude
5757
'./zotero-connectors/src/common/utilities.js',
58+
'./zotero-connectors/src/translate/src/promise.js',
5859
'./zotero-connectors/src/translate/src/translation/translate_item.js',
5960
'./zotero-connectors/src/common/translators.js', // backgroundInclude
6061
'./zotero-connectors/src/common/inject/http.js',
@@ -77,6 +78,7 @@ gulp.task('copy-external-scripts', async function() {
7778
'./zotero-connectors/src/utilities/utilities.js',
7879
'./zotero-connectors/src/utilities/utilities_item.js',
7980
'./zotero-connectors/src/utilities/schema.js',
81+
8082
'./zotero-connectors/src/translate/src/promise.js',
8183
'./zotero-connectors/src/translate/src/debug.js',
8284
'./zotero-connectors/src/translate/src/rdf/init.js',

0 commit comments

Comments
 (0)