-
Notifications
You must be signed in to change notification settings - Fork 4
/
background.js
69 lines (60 loc) · 1.85 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
/* global chrome */
const FORBIDDEN_PROTOCOLS = ['devtools:']
chrome.webNavigation.onDOMContentLoaded.addListener(handleLoaded)
/**
* ssb-fetch returns application/ssb+json for 'post' messages
* application/json for other message types
*/
const TYPE_MAP = {
'text/plain': 'markdown',
'text/markdown': 'markdown',
'text/gemini': 'gemini',
'application/json': 'json',
// TODO: Hooks for activitystream rendering?
'application/activity+json': 'json',
'application/ld+json': 'json',
'application/ssb+json': 'ssb'
}
const SCRIPT_MAP = {
markdown: scriptURL('markdown'),
gemini: scriptURL('gemini'),
json: scriptURL('json'),
ssb: scriptURL('ssb')
}
const code = `
(function (){
const TYPE_MAP = ${JSON.stringify(TYPE_MAP)}
const SCRIPT_MAP = ${JSON.stringify(SCRIPT_MAP)}
const knownType = TYPE_MAP[document.contentType]
if(knownType) {
const src = SCRIPT_MAP[knownType]
const script = document.createElement('script')
script.setAttribute('src', src)
script.setAttribute('charset', 'utf-8')
document.body.appendChild(script)
}
})()
`
console.log('Waiting to inject rendering code', { SCRIPT_MAP, TYPE_MAP })
chrome.browserAction.onClicked.addListener(({ id: tabId }) => {
const readerCode = `
(function (){
const src = "${scriptURL('reader')}"
const script = document.createElement('script')
script.setAttribute('src', src)
script.setAttribute('charset', 'utf-8')
document.body.appendChild(script)
})();
`
chrome.tabs.executeScript(tabId, { code: readerCode })
})
function handleLoaded ({ tabId, url }) {
const { protocol } = new URL(url)
if (FORBIDDEN_PROTOCOLS.includes(protocol)) return
// Detect if text/markdown/json/gemini by the contentType
// Then inject the relevant renderer script for the match
chrome.tabs.executeScript(tabId, { code })
}
function scriptURL (name) {
return chrome.runtime.getURL(`bundle-${name}.js`)
}