-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
91 lines (77 loc) · 2.6 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
85
86
87
88
89
90
91
class Corsify {
constructor() {
this.settings = {}
}
initialize() {
let gettingSettings = browser.storage.local.get('corsifySettings')
gettingSettings.then(settings => {
this.settings = settings.corsifySettings || {}
})
this.addBackgroundMessageListener()
}
addBackgroundMessageListener() {
browser.runtime.onMessage.addListener(message => {
let handleRequest = this.handleRequest.bind(this)
let handleResponse = this.handleResponse.bind(this)
this.settings = message.settings
if (message.type === 'enableCors') {
if (this.settings.enableCors) {
this.addWebRequestListeners()
} else {
browser.webRequest.onBeforeSendHeaders.removeListener(handleRequest)
browser.webRequest.onHeadersReceived.removeListener(handleResponse)
}
} else if (message.type === 'enforceCorsForAllURLs' || message.type === 'whiteListedURLs') {
browser.webRequest.onBeforeSendHeaders.removeListener(handleRequest)
browser.webRequest.onHeadersReceived.removeListener(handleResponse)
if(!this.settings.enableCors) {
return
}
this.addWebRequestListeners()
}
})
}
addWebRequestListeners() {
let handleRequest = this.handleRequest.bind(this)
let handleResponse = this.handleResponse.bind(this)
let urls = []
if (('enforceCorsForAllURLs' in this.settings) && this.settings.enforceCorsForAllURLs) {
urls = ['<all_urls>']
} else if (('whiteListedURLs' in this.settings) && Array.isArray(this.settings.whiteListedURLs) && this.settings.whiteListedURLs.length > 0) {
urls = this.settings.whiteListedURLs
} else {
return
}
browser.webRequest.onBeforeSendHeaders.addListener(
handleRequest,
{ urls },
['blocking', 'requestHeaders']
)
browser.webRequest.onHeadersReceived.addListener(
handleResponse,
{ urls },
['blocking', 'responseHeaders']
)
}
handleRequest() {}
handleResponse(response) {
let headersIndex = response.responseHeaders.length
while(--headersIndex) {
if(response.responseHeaders[headersIndex].name.toLowerCase() === 'access-control-allow-origin') {
response.responseHeaders[headersIndex].value = '*'
break
}
}
if (headersIndex === 0) { //if we didn't find it len will be zero
response.responseHeaders.push({
name: 'access-control-allow-origin',
value: '*'
})
}
return {
responseHeaders: response.responseHeaders
}
}
}
let corsifyInstance = new Corsify()
corsifyInstance.initialize()