forked from Ademking/BetterViewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
84 lines (70 loc) · 2.98 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
83
84
chrome.webRequest.onHeadersReceived.addListener(function (details) {
if (details.tabId !== -1) {
let header = getHeaderFromHeaders(details.responseHeaders, 'content-type');
let res = header && header.value.split(';', 1)[0];
// check if image
if (res && res.indexOf('image') !== -1) {
/**
* Note: I know this is not the best way to do this, but I don't know how to do it better
* I tried to abstract this but sometimes it doesn't work (when refreshing the image tab)
* https://stackoverflow.com/questions/21535233/injecting-multiple-scripts-through-executescript-in-google-chrome-extension
* My current solution is to use gulp to concat all the scripts and then inject them
* If you know a better way, please let me know
*/
chrome.tabs.executeScript(details.tabId, {
file: './dist/all.js',
}, function (res) {
chrome.tabs.insertCSS(details.tabId, {
file: './dist/all.css',
}, function (res) {
chrome.tabs.sendMessage(details.tabId, {
type: 'injected',
url: details.url,
});
})
});
// Remove "content-security-policy" header from the selected image to allow it to be loaded in the viewer
// Same idea from here : https://github.com/PhilGrayson/chrome-csp-disable/blob/master/background.js
for (let i = 0; i < details.responseHeaders.length; i++) {
if (details.responseHeaders[i].name.toLowerCase() === 'content-security-policy') {
details.responseHeaders[i].value = '';
}
}
return {
responseHeaders: details.responseHeaders
};
}
}
}, {
urls: ['*://*/*'],
types: ['main_frame']
}, ['responseHeaders', 'blocking']);
/**
* Helper function: get header from headers
* @param {header} headers
* @param {headerName} headerName
* @returns
*/
function getHeaderFromHeaders(headers, headerName) {
for (let i = 0; i < headers.length; ++i) {
let header = headers[i];
if (header.name.toLowerCase() === headerName) {
return header;
}
}
}
// when the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function (details) {
if (details.reason === "install") {
// Code to be executed on first install
chrome.tabs.create({
url: "https://betterviewer.surge.sh/welcome.html"
});
} else if (details.reason === "update") {
// When extension is updated
} else if (details.reason === "chrome_update") {
// When browser is updated
} else if (details.reason === "shared_module_update") {
// When a shared module is updated
}
});